#2287
Rearrange Characters to Make Target String
EasyHash TableStringCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m) |
| Space | O(1) | O(n + m) |
💡
Intuition
Time O(n + m)Space O(n + m)
The optimal approach counts the frequency of each character in both `s` and `target`, then calculates how many times we can form `target` based on the available characters in `s`. This is efficient and avoids unnecessary combinations.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each character in `s` and `target`.
- 2Step 2: For each character in `target`, calculate how many times we can use the characters from `s` to form `target`.
- 3Step 3: The result is the minimum number of times we can form `target` based on the limiting character.
solution.py9 lines
1from collections import Counter
2
3def maxCopiesOptimal(s, target):
4 s_count = Counter(s)
5 target_count = Counter(target)
6 copies = float('inf')
7 for char in target_count:
8 copies = min(copies, s_count[char] // target_count[char])
9 return copiesℹ
Complexity note: The time complexity is O(n + m) because we traverse both strings once to count characters, where n is the length of `s` and m is the length of `target`. The space complexity is O(n + m) due to the storage of character counts.
- 1Counting character frequencies is crucial for solving this problem efficiently.
- 2The limiting factor for forming the target string is the character that appears the least number of times in `s` relative to its requirement in `target`.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.