Number of Good Ways to Split a String — LeetCode 1525 Python Solution

MediumBit ManipulationHash TableStringDynamic Programming
Problem
#1525
Reading time
3 min

The problem

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

Example

Input
s = "aacaba"
Output
2
Explanation
There are 5 ways to split "aacaba" and 2 of them are good.

Python solution

Python
class Solution:
    def numSplits(self, s: str) -> int:
        cnt = Counter(s)
        vis = set()
        ans = 0
        for c in s:
            vis.add(c)
            cnt[c] -= 1
            if cnt[c] == 0:
                cnt.pop(c)
            ans += len(vis) == len(cnt)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1525. Number of Good Ways to Split a String is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1525. Number of Good Ways to Split a String?
LeetCode 1525. Number of Good Ways to Split a String is rated Medium on LeetCode.
What is the time complexity of LeetCode 1525. Number of Good Ways to Split a String?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1525. Number of Good Ways to Split a String?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1525. Number of Good Ways to Split a String cover?
LeetCode 1525. Number of Good Ways to Split a String is tagged Bit Manipulation, Hash Table, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview