Back to posts
LeetCode Challenge Day 62 β 1513. Number of Substrings With Only 1s
Nitin Ahirwal / November 16, 2025
LeetCode ChallengeDay 62Binary StringCountingMathJavaScriptMedium
Hey folks π
This is Day 62 of my LeetCode streak π
Todayβs problem is 1513 β Number of Substrings With Only 1s.
It looks simple at first glance, but the trick is to notice how consecutive 1s form substrings.
π‘ Intuition
When you see consecutive 1s:
- A run of length
1β contributes1 - A run of length
2β contributes1 + 2 = 3 - A run of length
3β contributes1 + 2 + 3 = 6
In general:
For a run of length L:
Total substrings = L Γ (L + 1) / 2
This gives a direct counting approach without generating substrings.
π Approach
- Iterate through the string left to right.
- Maintain a variable
runthat counts consecutive1s. - On every
'1':- Increment
run - Add
runto the answer
- Increment
- On
'0', resetrun = 0 - Keep everything modulo 1e9+7.
This converts a potentially O(nΒ²) substring problem into an efficient O(n) solution.
π Complexity
- Time Complexity:
O(n)β single pass - Space Complexity:
O(1)β constant auxiliary space
π§βπ» Code (JavaScript)
/**
* @param {string} s
* @return {number}
*/
var numSub = function(s) {
const MOD = 1000000007;
let ans = 0;
let run = 0;
for (let i = 0; i < s.length; ++i) {
if (s[i] === '1') {
run += 1;
ans = (ans + run) % MOD;
} else {
run = 0;
}
}
return ans;
};
π― Example
Input:
s = "0110111"
Output:
9
Because runs of 1s contribute:
-
1β 1 -
11β 3 -
111β 6
Total = 9
π§ Reflection
This problem reinforces the idea that many substring problems can be simplified by:
-
Recognizing run patterns
-
Using arithmetic formulas
-
Avoiding brute-force enumeration
See you tomorrow for Day 63! π
Happy Coding π¨βπ»β¨