Number of Substrings With Only 1s — LeetCode 1513 Python Solution

MediumMathString
Problem
#1513
Reading time
2 min

The problem

Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.

Example

Input
s = "0110111"
Output
9
Explanation
There are 9 substring in total with only 1's characters.

Python solution

Python
class Solution:
    def numSub(self, s: str) -> int:
        mod = 10**9 + 7
        ans = cur = 0
        for c in s:
            if c == "0":
                cur = 0
            else:
                cur += 1
                ans = (ans + cur) % mod
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1513. Number of Substrings With Only 1s is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1513. Number of Substrings With Only 1s?
LeetCode 1513. Number of Substrings With Only 1s is rated Medium on LeetCode.
What is the time complexity of LeetCode 1513. Number of Substrings With Only 1s?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 1513. Number of Substrings With Only 1s?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1513. Number of Substrings With Only 1s cover?
LeetCode 1513. Number of Substrings With Only 1s is tagged Math and String 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