Problem 485

Abstract / Summary

Find the longest sequence of consecutive 1s in a binary array.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0485.py

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        result = 0

        current = 0
        for i in nums:
            if i == 1:
                current += 1
                result = max(result, current)
            else:
                current = 0

        return result
13 lines | 321 bytes | submitted August 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic problem of determining the longest run of consecutive 1s in a binary array. It iterates through the input list once, maintaining a running count of the current streak of 1s and updating the best streak seen so far. The algorithm returns the length of the longest such streak.

Key Steps

Initialization

At the start of the method two integer variables are created.

result = 0
current = 0

result holds the maximum length discovered up to the current point, while current tracks the length of the ongoing sequence of 1s.

Iteration and Counting

The core of the solution is a single for loop that examines each element of the input list in order.

for i in nums:
    if i == 1:
        current += 1
        result = max(result, current)
    else:
        current = 0

When the element equals 1, the algorithm increments current, reflecting the continuation of a streak. Immediately after the increment, result is refreshed with the larger of its previous value and the new current. If the element is 0, the ongoing streak is broken and current is reset to 0, preparing for any future streak that may begin later in the array.

Result Return

After the loop finishes, the method returns the stored maximum.

return result

This final value represents the length of the longest contiguous block of 1s encountered during the scan.

Edge Cases Handled

The logic gracefully deals with several boundary conditions without additional code.

When the input list is empty, the loop body never executes; both result and current remain at their initial value of 0, and the method returns 0, which correctly indicates that no 1s are present.

If the array consists entirely of 0s, each iteration triggers the else branch, repeatedly resetting current to 0. The result never changes from its initial 0, so the method again returns 0.

When the array is composed solely of 1s, the if branch runs for every element. current grows with each step, and result is updated to match current each time. At loop termination, result equals the length of the array, correctly reflecting the maximal streak.

Mixed patterns of 1s and 0s are handled by the alternating increment and reset behavior, ensuring that only contiguous runs contribute to the count.

Performance Optimizations

The implementation achieves optimal efficiency by using a single pass over the input data. Maintaining only two scalar variables (result and current) means that the algorithm’s memory footprint stays constant regardless of input size.

The use of the built-in max function to update result avoids explicit conditional branches for comparison, allowing the interpreter to handle the operation efficiently.

Resetting current to 0 immediately upon encountering a 0 eliminates the need for additional state tracking or auxiliary data structures, further reducing overhead.

Overall, the design leverages straightforward control flow and minimal state to deliver fast execution with negligible auxiliary memory usage.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of building blocks spread out on the floor. Some of these blocks are shiny gold ones labeled with a one, and others are plain gray ones labeled with a zero. The goal is to walk down the row and find the longest stretch of shiny gold blocks standing side by side.

A little helper starts at the beginning of the row, keeping a tally of how many gold blocks have been seen in a row. Every time a gold block is found, the helper adds one to the tally and writes down how high the tally reached if it is the biggest number seen so far. If a gray block appears instead, it means the current stretch has been broken, so the tally resets back to zero. By the time the end of the row is reached, the helper remembers the highest number written down during the walk.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.41 | σ = 0.78

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python JS Go Rust PHP TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
pruthvikp Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vthwang Java
zfang399 C++
43 links | 27 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

12 easy
13 solutions   August 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality