Rearrange Characters to Make Target String — LeetCode 2287 Python Solution
EasyHash TableStringCounting
- Problem
- #2287
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.
Example
- Input
- s = "ilovecodingonleetcode", target = "code"
- Output
- 2
- Explanation
- For the first copy of "code", take the letters at indices 4, 5, 6, and 7.
Python solution
Python
class Solution:
def rearrangeCharacters(self, s: str, target: str) -> int:
cnt1 = Counter(s)
cnt2 = Counter(target)
return min(cnt1[c] // v for c, v in cnt2.items())Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + m) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2287. Rearrange Characters to Make Target String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2287. Rearrange Characters to Make Target String?
- LeetCode 2287. Rearrange Characters to Make Target String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2287. Rearrange Characters to Make Target String?
- The Python solution on this page runs in O(n + m).
- What is the space complexity of LeetCode 2287. Rearrange Characters to Make Target String?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 2287. Rearrange Characters to Make Target String cover?
- LeetCode 2287. Rearrange Characters to Make Target String is tagged Hash Table, String and Counting on LeetCode.