Number of Substrings With Only 1s — LeetCode 1513 Python Solution
- Problem
- #1513
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(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.