AlgoMaster Logo

Number of Good Ways to Split a String

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach involves using a nested loop to try every possible split point and count unique characters on both sides of the split. While this method is straightforward, it is inefficient because it involves recalculating the unique character count for both substrings at every possible split point.

Steps:

  1. Initialize a counter to keep track of good splits.
  2. Loop over possible split points from 1 to n-1 (where n is the length of the string).
  3. For each split point, split the string into two parts and count the unique characters in each part.
  4. If the number of unique characters in both parts is equal, increment the good split counter.

Code:

2. Optimized Approach using Frequency Maps

Intuition:

To improve efficiency, we can use two frequency maps to track character counts on both sides of the split. We start with all characters in the 'right' map, and as we process each character, we move it from the 'right' map to the 'left' map until the split point is found. This allows maintaining constant time complexity for adjusting character counts and only recalculates the number of unique characters at each split.

Steps:

  1. Initialize two integer arrays leftFreq and rightFreq to keep track of character occurrences on both sides.
  2. Traverse the string once to populate the rightFreq array.
  3. As we iterate over possible split points, adjust the counts in leftFreq and rightFreq as characters move from right to left.
  4. Use two counters leftUnique and rightUnique to track the number of unique characters in each partition as they evolve.
  5. Whenever these two counters are equal, it is a good split.

Code: