LeetCode 2287: Rearrange Characters to Make Target String Solution
Master LeetCode problem 2287 (Rearrange Characters to Make Target String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2287. Rearrange Characters to Make Target String
Problem Explanation
Explanation:
To solve this problem, we can count the frequency of each character in both strings s and target. We then calculate the maximum number of copies of target that can be formed by taking characters from s based on the frequency of characters in both strings.
- Create frequency maps for characters in strings
sandtarget. - Iterate over the characters in
targetand calculate the maximum number of copies based on the minimum frequency of each character. - Return the minimum count calculated in the previous step as the result.
Time Complexity:
- The time complexity of this approach is O(n), where n is the length of string
s.
Space Complexity:
- The space complexity is O(1) since the frequency map will have a fixed size of 26 lowercase English letters.
:
Solution Code
class Solution {
public int maxNumberOfCopies(String s, String target) {
int[] sFreq = new int[26];
int[] targetFreq = new int[26];
for (char ch : s.toCharArray()) {
sFreq[ch - 'a']++;
}
for (char ch : target.toCharArray()) {
targetFreq[ch - 'a']++;
}
int maxCopies = Integer.MAX_VALUE;
for (int i = 0; i < target.length(); i++) {
if (targetFreq[target.charAt(i) - 'a'] > 0) {
maxCopies = Math.min(maxCopies, sFreq[target.charAt(i) - 'a'] / targetFreq[target.charAt(i) - 'a']);
} else {
return 0;
}
}
return maxCopies;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2287 (Rearrange Characters to Make Target String)?
This page provides optimized solutions for LeetCode problem 2287 (Rearrange Characters to Make Target String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2287 (Rearrange Characters to Make Target String)?
The time complexity for LeetCode 2287 (Rearrange Characters to Make Target String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2287 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2287 in Java, C++, or Python.