1513. Number of Substrings With Only 1s
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Number of Substrings With Only 1s (Unknown) asks you to solve a structured algorithmic task. This is a common Math / String pattern in coding interviews. Count consecutive 1s ending at each position; each run of length k contributes k new substrings.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Count consecutive 1s ending at each position; each run of length k contributes k new substrings.
Related patterns: Math, String, Dynamic Programming
1513.cs
C#
// Approach: Count consecutive 1s ending at each position; each run of length k contributes k new substrings.
// Time: O(n) Space: O(1)
public class Solution
{
public int NumSub(string s)
{
// Define modulo constant to prevent integer overflow
const int MODULO = (int)1e9 + 7;
// Total count of valid substrings
int totalCount = 0;
// Current consecutive '1's count ending at current position
int consecutiveOnes = 0;
// Iterate through each character in the string
for (int i = 0; i < s.Length; i++)
{
// If current character is '1', increment consecutive count
// Otherwise, reset consecutive count to 0
if (s[i] == '1')
consecutiveOnes++;
else
consecutiveOnes = 0;
// Add current consecutive count to total
// This represents all substrings of '1's ending at position i
totalCount = (totalCount + consecutiveOnes) % MODULO;
}
return totalCount;
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 22. Generate Parentheses(Medium)
- 29. Divide Two Integers(Medium)
- 30. Substring with Concatenation of All Words(Hard)