← Home

1513. Number of Substrings With Only 1s

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
151

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1513. Number of Substrings With Only 1s, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • time: O(N), space: O(N)

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are moduloMultiplication, numSub.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(N)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 84 ms, faster than 25.00% of C++ online submissions for Number of Substrings With Only 1s.
02//Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Number of Substrings With Only 1s.
03//time: O(N), space: O(N)
04class Solution {
05public:
06    int moduloMultiplication(int a, int b, int mod) {
07        int res = 0; // Initialize result 
08
09        // Update a if it is more than 
10        // or equal to mod 
11        a %= mod;
12
13        while (b){ 
14            /*
15            If b is even then 
16            a * b = 2 * a * (b / 2), 
17            otherwise 
18            a * b = a + a * (b - 1)
19            */
20            // If b is odd, add 'a' to result 
21            if(b & 1){
22                res = (res + a) % mod;
23            }
24
25            // Here we assume that doing 2*a 
26            // doesn't cause overflow 
27            a = (2 * a) % mod; 
28
29            b >>= 1; // b = b / 2 
30        } 
31
32        return res; 
33    } 
34    
35    int numSub(string s) {
36        int MOD = 1e9+7;
37        
38        map<int, int> counter;
39        
40        int n = s.size();
41        
42        int len = 0;
43        
44        for(int i = 0; i <= n; ++i){
45            if(i == n || s[i] == '0'){
46                if(len > 1){
47                    // counter[1] is handled otherwhere
48                    // cout << "len: " << len << ", count increase" << endl;
49                    counter[len]++;
50                }
51                len = 0;
52            }else{
53                ++len;
54                counter[1]++;
55            }
56            // cout << "len: " << len << endl;
57        }
58        
59        int ans = 0;
60        
61        for(auto it = counter.begin(); it != counter.end(); ++it){
62            if(it->first == 1){
63                ans += it->second;
64            }else{
65                int a = it->first;
66                int b = it->first-1;
67                if(a % 2 == 0) a /= 2;
68                if(b % 2 == 0) b /= 2;
69                int t = moduloMultiplication(a, b, MOD);
70                t = moduloMultiplication(t, it->second, MOD);
71                ans += t;
72                // ans += (it->first) * (it->first-1) / 2 * it->second;
73            }
74        }
75        
76        return ans;
77    }
78};
79
80//https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731580/JavaC%2B%2BPython-Count
81//Runtime: 32 ms, faster than 100.00% of C++ online submissions for Number of Substrings With Only 1s.
82//Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Number of Substrings With Only 1s.
83//time: O(N), space: O(1)
84class Solution {
85public:
86    int numSub(string s) {
87        int count = 0, ans = 0;
88        int MOD = 1e9+7;
89        
90        for(char c : s){
91            if(c == '1'){
92                /*
93                for each new '1',
94                there will be more "count" substrings with all '1's
95                */
96                ++count;
97                ans = (ans + count) % MOD;
98            }else{
99                count = 0;
100            }
101        }
102        
103        return ans;
104    }
105};

Cost

Complexity

Time
O(N), space: O(N)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.