53. Same Letters, New Order
A word-game app lets players rearrange the tiles of one word to form another. Given two strings a and b of lowercase letters, decide whether b can be made by rearranging all the letters of a, using every letter of a exactly once and no others.
Return true if so, otherwise false. Two identical words count as a valid rearrangement of each other. Sorting both strings works, but aim for a linear-time solution that counts how many times each of the 26 letters occurs.
Example 1
- Input:
- a = "stressed", b = "desserts"
- Output:
- true
- Explanation:
Both words contain the same letters with the same counts, so the answer is true.
Example 2
- Input:
- a = "abc", b = "abd"
- Output:
- false
- Explanation:
The last letters differ (c versus d), so the answer is false.
Constraints
1 ≤ a.length, b.length ≤ 5 * 104
a and b contain only lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)