Understanding the Problem
We are given a binary array — an array consisting only of 1s and 0s. The goal is to find the length of the longest contiguous sequence of 1s.
That means we want to count how many 1s appear in a row without being interrupted by a 0. As soon as we hit a 0, the streak is broken, and we start counting again.
Step-by-Step Approach (with Example)
Let’s take the example array: [1, 1, 0, 1, 1, 1]
Step 1: Initialize two counters
current_count
: to keep track of the current streak of 1s.
max_count
: to remember the highest streak we've seen so far.
Step 2: Loop through the array
- Start from the first element and go to the end.
- If the element is
1
: increment current_count
.
- If the element is
0
: reset current_count
to 0.
- At each step, update
max_count
to be the maximum of itself and current_count
.
Step 3: Final Result
After the loop, max_count
will hold the longest stretch of 1s.
Detailed Walkthrough for [1, 1, 0, 1, 1, 1]
- Start:
current_count = 0
, max_count = 0
- Index 0: 1 →
current_count = 1
, max_count = 1
- Index 1: 1 →
current_count = 2
, max_count = 2
- Index 2: 0 →
current_count = 0
, max_count = 2
- Index 3: 1 →
current_count = 1
, max_count = 2
- Index 4: 1 →
current_count = 2
, max_count = 2
- Index 5: 1 →
current_count = 3
, max_count = 3
Final answer: 3
Incorporating Edge Cases
1. All 1s: [1, 1, 1, 1]
The entire array is one continuous sequence of 1s → Output: 4
2. All 0s: [0, 0, 0]
No 1s present at all → Output: 0
3. Isolated 1s: [1, 0, 1, 0, 1]
Each 1 is surrounded by 0s → Maximum streak = 1
4. Empty Array: []
No elements means no 1s → Output: 0
Efficiency
This approach uses only one pass through the array (O(n) time complexity) and does not use any extra space. It’s optimal and beginner-friendly.
Comments
Loading comments...