#1525
Number of Good Ways to Split a String
MediumHash TableStringDynamic ProgrammingBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses two hash maps to keep track of the distinct character counts for the left and right parts of the string as we iterate through it. This allows us to efficiently compare counts without needing to recreate substrings.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two hash maps to count characters in the left and right parts of the string.
- 2Step 2: Populate the right hash map with all characters from the string.
- 3Step 3: Iterate through the string, updating the left hash map and removing characters from the right hash map as you go.
- 4Step 4: After each character addition, compare the sizes of the two hash maps. If they are equal, increment the good split count.
- 5Step 5: Return the total count of good splits.
solution.py14 lines
1def numSplits(s):
2 left_count, right_count = {}, {}
3 for char in s:
4 right_count[char] = right_count.get(char, 0) + 1
5 good_splits = 0
6 for i in range(len(s) - 1):
7 char = s[i]
8 left_count[char] = left_count.get(char, 0) + 1
9 right_count[char] -= 1
10 if right_count[char] == 0:
11 del right_count[char]
12 if len(left_count) == len(right_count):
13 good_splits += 1
14 return good_splitsℹ
Complexity note: The time complexity is O(n) because we make a single pass through the string to populate the right hash map and another pass to check splits. The space complexity is O(n) due to the storage of character counts in the hash maps.
- 1Using hash maps allows efficient counting of distinct characters.
- 2Iterating through the string while updating counts helps avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.