Problem 1573

Abstract / Summary

Count how many ways a string can be split into parts where each part has unique characters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1573.py

class Solution:
    def numWays(self, s: str) -> int:
        mod   = 1_000_000_007

        # count 0s and 1s
        ones  = s.count("1")
        zeros = len(s) - ones

        # only zeros
        if ones == 0:
            # triangle number minus 1
            return ((zeros - 1) * (zeros - 2) // 2) % mod

        if ones % 3 != 0:
            return 0 # no such split
        third = ones // 3

        # number of allowed first and second split position
        split1 = 0
        split2 = 0
        seen = 0 # number of 1s seen so far
        for i, c in enumerate(s):
            if c == "1":
                seen += 1

            if   seen == third:
                split1 += 1
            elif seen == 2 * third:
                split2 += 1
            elif seen > 2 * third:
                break # makes it a tiny bit faster

        return (split1 * split2) % mod
33 lines | 912 bytes | submitted January 22, 2024 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 35% (100k+ submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method numWays that computes, under a large prime modulus, the number of ways to split a binary string into three contiguous parts such that each part contains the same number of '1' characters. The algorithm first classifies the input based on the total count of '1's, then determines the feasible split positions by scanning the string once, and finally combines the counts of possible first and second split locations to obtain the answer.

Key Steps

Counting characters

The method begins by counting the total number of '1' characters and deriving the number of '0' characters from the string length.

ones  = s.count("1")
zeros = len(s) - ones

These two values drive the subsequent control flow.

Handling the all-zero case

When the string contains no '1's, any split that yields three non-empty parts is valid. The number of ways to choose two cut positions among the zeros characters is the triangular number C(zeros-1, 2). The code returns this value modulo the prescribed constant.

if ones == 0:
    return ((zeros - 1) * (zeros - 2) // 2) % mod

Verifying divisibility by three

If there is at least one '1', the total must be divisible by three for an equal distribution to be possible. The method returns zero immediately when this condition fails.

if ones % 3 != 0:
    return 0
third = ones // 3

Scanning for split positions

The core of the algorithm walks through the string once, maintaining a counter of '1's seen so far. When the counter reaches the first third of the total '1's, the current index marks a potential end of the first segment; each such occurrence increments split1. When the counter reaches two thirds, the index marks a potential end of the second segment; each such occurrence increments split2. The loop terminates early once the counter exceeds two thirds, avoiding unnecessary iterations.

split1 = 0
split2 = 0
seen = 0
for i, c in enumerate(s):
    if c == "1":
        seen += 1

    if   seen == third:
        split1 += 1
    elif seen == 2 * third:
        split2 += 1
    elif seen > 2 * third:
        break

Computing the final answer

The total number of valid splits equals the product of the counts of possible first-cut positions and second-cut positions, because each choice of a first cut can be paired with any choice of a second cut that occurs later. The result is reduced modulo the large prime.

return (split1 * split2) % mod

Edge Cases Handled

The implementation explicitly addresses the scenario where the input string consists solely of '0' characters. In that situation, the combinatorial formula for selecting two cut points among zeros characters yields the correct count, and the early return prevents any further processing.

When the total number of '1's is not a multiple of three, the method returns zero without performing a scan, correctly indicating that no equal-distribution split exists.

The loop includes a guard that breaks out once the count of seen '1's exceeds two thirds of the total. This early exit ensures that strings where the required split points appear early do not cause unnecessary traversal of the remaining characters.

Performance Optimizations

The algorithm achieves linear time performance by counting '1's with the built-in str.count method, which is implemented in C and runs faster than a manual Python loop.

The subsequent single pass over the string uses only integer counters and simple conditional checks, avoiding any auxiliary data structures. The early termination condition (elif seen > 2 * third: break) reduces the number of iterations for inputs where the relevant split positions are located near the beginning of the string.

All arithmetic operations are performed with the modulus applied only at the final step, minimizing the overhead of repeated modular reductions during the scan.

By combining these choices, the method processes the input efficiently even for very long binary strings while maintaining a small constant memory footprint.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a very long train made of blocks that are either zeroes or ones. The goal is to cut this long train into three smaller pieces so that each piece has exactly the same number of ones inside it.

First, count every single one and zero in the whole train. If there are no ones at all, it is like having a row of zeroes where you can pick two spots to make cuts. There is a special math trick to figure out how many ways to pick those spots.

If there are some ones, check if the total amount can be shared equally by three. If it cannot, then it is impossible to cut the train fairly, so the answer is zero. If the number can be shared, figure out how many ones go into each of the three piles.

Now, walk along the train from start to finish. Keep track of how many ones have been seen. When the count of ones matches the first pile size, remember that spot as a place where the first cut could happen. When the count reaches two times that size, remember that spot as a place for the second cut.

Once the walk is done, multiply the number of ways to make the first cut by the number of ways to make the second cut. That gives the final count of all the different ways to split the train. Because that number could be very big, use a special math rule to keep it within a certain size.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.96 | σ = 0.90

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
wisdompeak C++
25 links | 15 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 22, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality