easyLeetCodeNot Started

Max Consecutive Ones

A curated StudyFlow practice problem with comprehensive editorial and multi-language solutions.

Solve on LeetCode
Lesson

Problem Statement

Given a binary array nums, return *the maximum number of consecutive* 1*'s in the array*.

Example 1 · Standard Case with Intermittent Zeros:

Input: nums = [1, 1, 0, 1, 1, 1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2 · Mixed Sequence:

Input: nums = [1, 0, 1, 1, 0, 1]
Output: 2
Explanation: Consecutive 1s runs are of lengths 1, 2, and 1. The maximum is 2.

Example 3 · All Zeros Array:

Input: nums = [0, 0, 0]
Output: 0
Explanation: There are no 1s, so the maximum consecutive 1s is 0.

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.

Prerequisites

Before attempting this problem, you should be comfortable with:

  • Linear array iteration (for loop)
  • Conditionals (if-else)
  • Maintaining running minimum/maximum variables

What You'll Learn

Key principles and algorithmic techniques you will master from this problem:

  • Master single-pass state tracking with running streak variables.
  • Formulate optimal linear O(N) scans with zero extra memory O(1).
  • Avoid trailing edge-case bugs by updating global max continuously.

Pattern Recognition Trigger

How to instantly recognize this algorithmic pattern when encountering unseen interview questions:

Signals to Look For:

  • Finding longest contiguous subarray satisfying a single-character/value condition.
  • Binary array stream where encountering a delimiter (0) resets current progress.
  • Linear scan tracking current streak vs global best streak.

Algorithmic Decision Tree:

  • When counting consecutive matching elements: Use a running count that increments on match and resets to 0 on mismatch, continually updating maxVal.

Connected Patterns:

Two PointersSliding WindowPrefix Sum

1. Nested Loops All Subarrays

Intuition

Check every starting position i and extend subarray while elements are 1, tracking max length.

Algorithm

  1. 1. Initialize maxLen = 0.
  2. 2. For i from 0 to n-1: - If nums[i] == 1, iterate j from i to n-1 while nums[j] == 1. - maxLen = max(maxLen, j - i).
  3. 3. Return maxLen.

Nested Loops All Subarrays

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [1, 1, 0, 1, 1, 1]
Current operationSTEP 1 OF 6
Phase 1 — Start from Index 0: Check subarray starting at index 0
Visual state
Values and pointers at this exact step
array
S
1
1
0
1
1
1
0
↑ Streak 2
1
2
3
4
5
Variables at this step
Streak
2
maxStreak
2
Check / comparison
Streak 1: [1, 1] -> len = 2.
Decision / next transition
maxStreak = 2.
Why this step matters

Phase 1 — Start from Index 0: Check subarray starting at index 0. nums[0]=1, nums[1]=1, nums[2]=0 (streak broken). Length = 2.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5#include <unordered_map>
6#include <unordered_set>
7#include <queue>
8#include <stack>
9#include <numeric>
10#include <climits>
11
12using namespace std;
13
14class Solution {
15public:
16 int findMaxConsecutiveOnes(vector<int>& nums) {
17 int n = nums.size();
18 int maxLen = 0;
19 for (int i = 0; i < n; ++i) {
20 if (nums[i] == 1) {
21 int count = 0;
22 for (int j = i; j < n && nums[j] == 1; ++j) {
23 count++;
24 }
25 maxLen = max(maxLen, count);
26 }
27 }
28 return maxLen;
29 }
30};
31
32int main() {
33 Solution sol;
34 vector<int> nums = {1, 1, 0, 1, 1, 1};
35 int ans = sol.findMaxConsecutiveOnes(nums);
36 cout << "Max Consecutive Ones: " << ans << endl;
37 return 0;
38}

Time & Space Complexity

  • Time complexity: O(N^2) — In the worst case (all 1s), the nested loop checks O(N2) elements.
  • Space complexity: O(1) — Auxiliary space is O(1).

Why Brute Force Doesn't Scale:

For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.

The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.


2. Two Pointers / Sliding Window

Intuition

Maintain two pointers (left and right) representing the current active window of 1s.

Algorithm

  1. 1. Initialize left = 0, maxLen = 0.
  2. 2. For right from 0 to n-1: - If nums[right] == 0, set left = right + 1. - Else maxLen = max(maxLen, right - left + 1).
  3. 3. Return maxLen.

Two Pointers / Sliding Window

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [1, 1, 0, 1, 1, 1]
Current operationSTEP 1 OF 6
Phase 1 — Expand Window 1: L = 0, R advances to 1
Visual state
Values and pointers at this exact step
array
S
1
1
0
1
1
1
0
↑ L=0
1
↑ R=1
2
3
4
5
Variables at this step
L
0
R
1
Len
2
maxLen
2
Check / comparison
Window [0..1] contains all 1s.
Decision / next transition
maxLen = 2.
Why this step matters

Phase 1 — Expand Window 1: L = 0, R advances to 1. Both are 1s. Window length = R - L + 1 = 1 - 0 + 1 = 2.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5#include <unordered_map>
6#include <unordered_set>
7#include <queue>
8#include <stack>
9#include <numeric>
10#include <climits>
11
12using namespace std;
13
14class Solution {
15public:
16 int findMaxConsecutiveOnes(vector<int>& nums) {
17 int left = 0, maxLen = 0;
18 for (int right = 0; right < nums.size(); ++right) {
19 if (nums[right] == 0) {
20 left = right + 1;
21 } else {
22 maxLen = max(maxLen, right - left + 1);
23 }
24 }
25 return maxLen;
26 }
27};
28
29int main() {
30 Solution sol;
31 vector<int> nums = {1, 1, 0, 1, 1, 1};
32 int ans = sol.findMaxConsecutiveOnes(nums);
33 cout << "Max Consecutive Ones: " << ans << endl;
34 return 0;
35}

Time & Space Complexity

  • Time complexity: O(N) — Right pointer makes a single linear scan from 0 to N-1, taking O(N) time.
  • Space complexity: O(1) — Auxiliary space is O(1).

3. Single-Pass Running Counter

Intuition

Traverse nums once with a running counter; increment on 1, reset to 0 on 0, and update max.

Algorithm

  1. 1. Initialize count = 0, maxCount = 0.
  2. 2. For each num in nums: - If num == 1: count++, maxCount = max(maxCount, count) - Else: count = 0.
  3. 3. Return maxCount.

Single-Pass Running Counter (O(N) Time, O(1) Space)

2 of 2 questions left today
Step 1 / 6
Trace timeline17% explored
InputINPUT nums = [1, 1, 0, 1, 1, 1]
Current operationSTEP 1 OF 6
Phase 1 — Scan Index 0: nums[0] is 1
Visual state
Values and pointers at this exact step
array
S
1
1
0
1
1
1
0
↑ count=1
1
2
3
4
5
Variables at this step
i
0
count
1
maxCount
1
Check / comparison
nums[0] == 1 -> count = 1.
Decision / next transition
maxCount = 1.
Why this step matters

Phase 1 — Scan Index 0: nums[0] is 1. Increment count: count = 1. maxCount = max(0, 1) = 1.

Step 1 / 6
C++ SOLUTIONCLEAN & OPTIMIZED
1#include <iostream>
2#include <vector>
3#include <string>
4#include <algorithm>
5#include <unordered_map>
6#include <unordered_set>
7#include <queue>
8#include <stack>
9#include <numeric>
10#include <climits>
11
12using namespace std;
13
14class Solution {
15public:
16 int findMaxConsecutiveOnes(vector<int>& nums) {
17 int count = 0, maxCount = 0;
18 for (int num : nums) {
19 if (num == 1) {
20 count++;
21 maxCount = max(maxCount, count);
22 } else {
23 count = 0;
24 }
25 }
26 return maxCount;
27 }
28};
29
30int main() {
31 Solution sol;
32 vector<int> nums = {1, 1, 0, 1, 1, 1};
33 int ans = sol.findMaxConsecutiveOnes(nums);
34 cout << "Max Consecutive Ones: " << ans << endl;
35 return 0;
36}

Time & Space Complexity

  • Time complexity: O(N) — A single traversal of array of size N takes O(N) time.
  • Space complexity: O(1) — Requires only two integer variables. Space is O(1).

Approach Comparison Matrix

Side-by-side comparison of time, space, and algorithmic trade-offs across each approach:

ApproachTimeSpaceCore IdeaTrade-off / Bottleneck
1.Approach 1: Nested Loops All SubarraysO(N^2)O(1)Check every starting position i and extend subarray while elements are 1, tracking max length.Repeated redundant scans over the input.
2.Approach 2: Two Pointers / Sliding WindowO(N)O(1)Maintain two pointers (left and right) representing the current active window of 1s.Auxiliary memory allocation or sorting step.
3.Approach 3: Single-Pass Running CounterOptimalO(N)O(1)Traverse nums once with a running counter; increment on 1, reset to 0 on 0, and update max.None. Asymptotically optimal.

Common Pitfalls & Crucial Edge Cases

Off-by-One Errors

Incorrect boundary indexing when adjusting pointers or array slices.

Integer Overflow

Using 32-bit signed integer types when accumulative operations exceed 231 - 1 in C++/Java.

Unnecessary Memory Allocation

Allocating large auxiliary arrays or objects inside inner loops causing GC overhead.

Failing to Reset Loop State

Not re-initializing state variables or counters between iterations or subproblems.

Crucial Edge Cases to Validate:

  • All Ones [1, 1, 1, 1] — Input: `, Expected: ` —
  • All Zeros [0, 0, 0] — Input: `, Expected: ` —
  • Alternating Elements [1, 0, 1, 0, 1] — Input: `, Expected: ` —

Interview Tips & Best Practices

How to communicate your thought process and address follow-ups in a live technical interview:

  1. Always state the brute force baseline before presenting the optimal solution to demonstrate structured problem solving.
  2. Explicitly verify boundary conditions (empty arrays, single elements, duplicates, extremes) out loud with the interviewer.
  3. Analyze both time and auxiliary space complexities clearly, explaining trade-offs between speed and memory allocation.

Quick Comprehension Check

Test your intuitive understanding of the core concept in 30 seconds:

1.What is the optimal time and auxiliary space complexity for Max Consecutive Ones?

2.Why is the brute force approach suboptimal for large inputs in Max Consecutive Ones?

3.Which data structure or technique enables the optimal solution for Max Consecutive Ones?