Problem 1513

Abstract / Summary

Count how many substrings made only of 1s exist in a binary string.

Note

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

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
13 lines | 292 bytes | submitted May 2, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (200k+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

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++
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++
27 links | 17 authors | 8 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

7 solutions   May 2, 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