← Home

1248. Count Number of Nice Subarrays

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
124

Let's make this one less mysterious. For 1248. Count Number of Nice Subarrays, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: two pointers, sliding window.

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

  • TLE
  • 23 / 38 test cases passed.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are numberOfSubarrays.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • 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. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

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) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//TLE
02//23 / 38 test cases passed.
03class Solution {
04public:
05    int numberOfSubarrays(vector<int>& nums, int k) {
06        int left = 0, right = 0;
07        int ans = 0;
08        
09        for(; left < nums.size(); left++){
10            int odds = 0;
11            right = left;
12            while(odds < k && right < nums.size()){
13                if(nums[right]%2 == 1){
14                    odds++;
15                }
16                // cout << left << right << odds << endl;
17                right++;
18            }
19            right--;
20            // cout << left << right << odds << endl;
21            
22            //if right is valid, then we've found a nice sub-array
23            if(right < nums.size() && odds == k){
24                ans++;
25                // cout << left << right << odds << ans << endl;
26                
27                //remaining nice subarray starting from "left"
28                right++;
29                while(right < nums.size() && nums[right]%2 == 0){
30                    ans++;
31                    // cout << left << right << odds << ans << endl;
32                    right++;
33                }
34            }
35        }
36        
37        return ans;
38    }
39};
40
41//Runtime: 200 ms, faster than 37.86% of C++ online submissions for Count Number of Nice Subarrays.
42//Memory Usage: 16.1 MB, less than 100.00% of C++ online submissions for Count Number of Nice Subarrays.
43class Solution {
44public:
45    int numberOfSubarrays(vector<int>& nums, int k) {
46        int left = 0, right = 0;
47        int ans = 0;
48        int odds = 0;
49        
50        for(; left < nums.size(); left++){
51            //sliding window
52            if(left > 0 && nums[left-1]%2 == 1){
53                odds--;
54            }
55            //if left == 0, it's first time
56            //o.w., it's not first time and nums[right] has been considered
57            //so here use "right++" to skip nums[right]
58            if(left > 0){
59                right++;
60            }
61            while(odds < k && right < nums.size()){
62                if(nums[right]%2 == 1){
63                    odds++;
64                }
65                // cout << left << right << odds << endl;
66                right++;
67            }
68            right--;
69            // cout << left << right << odds << endl;
70            
71            //if right is valid, then we've found a nice sub-array
72            if(right < nums.size() && odds == k){
73                ans++;
74                // cout << left << right << odds << ans << endl;
75                
76                //remaining nice subarray starting from "left"
77                int head = right;
78                vector<int>::iterator it = find_if(nums.begin()+head+1,
79                    nums.end(), 
80                    [](int e){return e%2 == 1;});
81                //remaining valid head's value: [head+1, it-1]
82                ans += (it-1 - (nums.begin()+head));
83                // cout << left << head << odds << ans << endl;
84            }
85        }
86        
87        return ans;
88    }
89};
90
91//https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/508217/C%2B%2B%3A-Visual-explanation.-O(1)-space.-Two-pointers
92//Runtime: 172 ms, faster than 95.48% of C++ online submissions for Count Number of Nice Subarrays.
93//Memory Usage: 15.7 MB, less than 100.00% of C++ online submissions for Count Number of Nice Subarrays.
94//time: O(n), space: O(1)
95class Solution {
96public:
97    int numberOfSubarrays(vector<int>& nums, int k) {
98        int left = 0, odds = 0, count = 0, ans = 0;
99        for(int right = 0; right < nums.size(); right++){
100            if(nums[right] % 2 == 1){
101                odds++;
102                if(odds >= k){
103                    count = 1;
104                    //move left bound while counting
105                    while(nums[left++] % 2 == 0){
106                        count++;
107                    }
108                    ans += count;
109                }
110            }else if(odds >= k){
111                //we already have "count" subarrays of [left, last right with odd number]
112                //now right points to an even number, we get "count" subarrays of [left, right]
113                ans += count;
114            }
115            // cout << "[" << left << ", " << right << "]: " << odds << ", " << count << ", " << ans << endl;
116        }
117        return ans;
118    }
119};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
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.