Number of Good Ways to Split a String - Problem

You are given a string s.

A split is called good if you can split s into two non-empty strings s_left and s_right where their concatenation is equal to s (i.e., s_left + s_right = s) and the number of distinct letters in s_left and s_right is the same.

Return the number of good splits you can make in s.

Input & Output

Example 1 — Multiple Good Splits
$ Input: s = "aacaba"
Output: 2
💡 Note: Split at index 2: "aa" (1 unique: a) | "caba" (3 unique: a,b,c) → 1≠3. Split at index 3: "aac" (2 unique: a,c) | "aba" (2 unique: a,b) → 2=2 ✓. Split at index 5: "aacab" (3 unique: a,c,b) | "a" (1 unique: a) → 3≠1. Only 1 good split, but checking all positions gives us 2 total good splits.
Example 2 — No Good Splits
$ Input: s = "abcd"
Output: 1
💡 Note: Split at index 1: "a" (1 unique) | "bcd" (3 unique) → 1≠3. Split at index 2: "ab" (2 unique) | "cd" (2 unique) → 2=2 ✓. Split at index 3: "abc" (3 unique) | "d" (1 unique) → 3≠1. There is 1 good split.
Example 3 — All Same Characters
$ Input: s = "aaaa"
Output: 3
💡 Note: Any split will have 1 unique character on both sides: "a"|"aaa", "aa"|"aa", "aaa"|"a" all have equal unique counts.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of only lowercase English letters

Visualization

Tap to expand
Good Ways to Split a String INPUT String s = "aacaba" a 0 a 1 c 2 a 3 b 4 a 5 Possible Split Positions: pos 1: "a" | "acaba" pos 2: "aa" | "caba" pos 3: "aac" | "aba" pos 4: "aaca" | "ba" pos 5: "aacab" | "a" Unique Characters Total: {a, b, c} = 3 Count: a=4, b=1, c=1 ALGORITHM STEPS 1 Initialize Hash Maps left_map={}, right_map=all chars 2 Scan Left to Right Add char to left, remove from right 3 Track Distinct Count Count unique chars in each part 4 Compare and Count If left_cnt == right_cnt: good++ Processing Each Split: i=1: L={a:1}=1, R={a,b,c}=3 i=2: L={a:2}=1, R={a,b,c}=3 i=3: L={a,c}=2, R={a,b}=2 [OK] i=4: L={a,c}=2, R={a,b}=2 [OK] i=5: L={a,b,c}=3, R={a}=1 Good splits: 2 FINAL RESULT Good Splits Found: Split at position 3 "aac" | "aba" 2 distinct = 2 distinct Split at position 4 "aaca" | "ba" 2 distinct = 2 distinct Output: 2 [OK] Verified 2 good ways found Key Insight: Use two hash maps to track distinct character counts for left and right parts. Start with all characters in right_map. As we scan, move chars from right to left. When distinct counts match, we found a good split. Time: O(n), Space: O(26) = O(1) for lowercase letters. TutorialsPoint - Number of Good Ways to Split a String | Hash Map Approach
Asked in
Amazon 15 Google 12
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen