← Home

525. Contiguous Array

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

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 525. Contiguous Array, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. 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:

  • Approach #1 Brute Force
  • TLE
  • 32 / 555 test cases passed.
  • time: O(N^2), space: O(1)

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 findMaxLength, arr.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • 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. 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), 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//Approach #1 Brute Force
02//TLE
03//32 / 555 test cases passed.
04//time: O(N^2), space: O(1)
05class Solution {
06public:
07    int findMaxLength(vector<int>& nums) {
08        int ans = 0;
09        
10        for(int start = 0; start < nums.size(); start++){
11            int zeros = 0, ones = 0;
12            for(int end = start; end < nums.size(); end++){
13                if(nums[end] == 0){
14                    zeros++;
15                }else{
16                    ones++;
17                }
18                if(zeros == ones){
19                    ans = max(ans, end-start+1);
20                }
21            }
22        }
23        
24        return ans;
25    }
26};
27
28//Approach #2 Using Extra Array [Accepted]
29//Runtime: 96 ms, faster than 90.38% of C++ online submissions for Contiguous Array.
30//Memory Usage: 20 MB, less than 41.67% of C++ online submissions for Contiguous Array.
31//time: O(N), space: O(N)
32class Solution {
33public:
34    int findMaxLength(vector<int>& nums) {
35        /*
36        key: count, ranges from -n to n
37        (shifted n to the right, so count = -n takes the index 0)
38        value: the end index of previous subarray whose count is the key
39        */
40        vector<int> arr(2*nums.size()+1, -2);
41        
42        /*
43        the start of subarray with count equaling to 0 starts from index 0,
44        this is equivalent to saying a previous subarray with count 0 ends at index -1
45        */
46        arr[nums.size()] = -1; //arr[nums.size()] corresponds to count = 0
47        int ans = 0, count = 0;
48        
49        for(int i = 0; i < nums.size(); i++){
50            count += (nums[i] == 0 ? -1 : 1);
51            //the index "count + nums.size()" corresponds to count = "count"
52            if(arr[count + nums.size()] >= -1){
53                /*
54                the initial value in "arr" is -2, 
55                so if its value >= -1, the value is meaningful
56                
57                when count is 0, we will enter this part automatically,
58                e.g. [0, 0, 1, 1], when "i" is 3, 
59                i-arr[count+nums.size()] will be 4,
60                that means we can find a continuous array from the start of nums
61                
62                i is the ending index of current subarray with specific count,
63                arr[count+nums.size()] is previous subarray with the same count
64                i-arr[count+nums.size()] is then the length of subarray with count equaling to 0 
65                */
66                ans = max(ans, i-arr[count+nums.size()]);
67            }else{
68                /*
69                the value in current index is meaningless,
70                so we update it
71                
72                subarray of "count" ends at i
73                next time when we meet subarray with the same count,
74                we can calculate the length of that subarray by 
75                subtracting arr[count+nums.size()] from index at that time 
76                */
77                arr[count+nums.size()] = i;
78            }
79        }
80        
81        return ans;
82    }
83};
84
85//Approach #3 Using HashMap [Accepted]
86//Runtime: 180 ms, faster than 46.37% of C++ online submissions for Contiguous Array.
87//Memory Usage: 17.7 MB, less than 100.00% of C++ online submissions for Contiguous Array.
88//time: O(N), space: O(N)
89class Solution {
90public:
91    int findMaxLength(vector<int>& nums) {
92        //count can range from -n to n
93        unordered_map<int, int> count2index;
94        count2index[0] = -1;
95        
96        int ans = 0, count = 0;
97        
98        for(int i = 0; i < nums.size(); i++){
99            count += (nums[i] == 0 ? -1 : 1);
100            if(count2index.find(count) != count2index.end()){
101                // cout << i << ": " << count << " -> len: " << i-count2index[count] << endl;
102                /*
103                the interval [0, count2index[count]] has count2index[count] more 1 than 0,
104                and so does  the interval [0, i], 
105                so the interval [count2index[count]+1, i] has equal 0s and  1s
106                */
107                ans = max(ans, i-count2index[count]);
108            }else{
109                // cout << i << ": " << count << " -> ix: " << i << endl;
110                count2index[count] = i;
111            }
112        }
113        
114        return ans;
115    }
116};

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.