Python 1513.py
class Solution:
def numSub(self, s: str) -> int:
result = 0
ones = 0
for c in s:
if c == "1":
ones += 1
result += ones
else:
ones = 0
return result % 1_000_000_007
Difficulty
and has an acceptance rate of about 57% (200k+ submissions).
Typical patterns to solve this problem:
- Math
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method numSub that receives a binary string s. Its purpose is to count the total number of substrings that consist exclusively of the character '1'. The method accumulates this count while iterating through the input once, and finally returns the result reduced modulo 1 000 000 007.
Core Logic
The algorithm maintains two integer variables: result, which aggregates the total number of qualifying substrings, and ones, which tracks the length of the current consecutive run of '1' characters. As the loop processes each character, ones is either incremented (when the character is '1') or reset to zero (when the character is '0'). Each time a '1' is encountered, the current run length is added to result. This incremental addition captures all new substrings that end at the current position.
result = 0
ones = 0
for c in s:
if c == "1":
ones += 1
result += ones
else:
ones = 0
After the traversal, the method applies the required modulus operation before returning the final count.
return result % 1_000_000_007
Edge-Case Handling
When the input string is empty, the loop body never executes, leaving result at its initial value of zero. The final modulo operation therefore returns zero, which correctly represents the absence of any substrings.
If the string contains only '0' characters, each iteration triggers the else branch, resetting ones to zero repeatedly. No addition to result occurs, and the method again returns zero after the modulo step.
For a string composed entirely of '1' characters, ones grows monotonically with each iteration. The cumulative addition result += ones yields the triangular number corresponding to the length of the string, which matches the total count of all-ones substrings.
The modulo operation safeguards the result against overflow even when the input length is very large, ensuring that the returned value always fits within the specified range.
Performance Optimizations
The solution achieves its goal with a single linear pass over the input, avoiding any nested loops or auxiliary data structures. By updating result incrementally rather than recomputing counts for each possible substring, the algorithm eliminates redundant work. The use of a constant-time modulo operation only once at the end, instead of after each addition, reduces the overhead associated with repeated large-integer arithmetic. Memory consumption stays constant because only two integer counters are maintained regardless of input size.
ELI5 - Simplified Explanation
Imagine this code is like a little robot helper that looks at a long line of blocks. Some of the blocks are ones and some of them are zeros. The robot wants to find out how many different ways it can pick a set of only ones that are sitting right next to each other.
The robot starts with a notebook set to zero. It moves along the line of blocks one by one to see what it finds. When it spots a one, it gets excited and adds to its count of how many ones it has seen in a row. It then adds that count to its notebook. If the robot finds a zero instead, it knows the chain of ones has stopped, so it resets its count of ones back to zero and keeps moving to look for more. By doing this, the robot keeps track of every possible group of ones along the whole line. Once it finishes looking at every block, the total number in the notebook tells the answer.
Code Quality
Complexity Analysis
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
Other Solutions
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++ | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++ | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 1759: Count Number of Homogenous Substrings
Solved On The Same Day
- problem 2572: Count the Number of Square-Free Subsets
- problem 2575: Find the Divisibility Array of a String
- problem 2680: Maximum OR
- problem 2685: Count the Number of Complete Components
- problem 3080: Mark Elements on Array by Performing Queries
- problem 3081: Replace Question Marks in String to Minimize Its Value
Extra
- 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