Neural Mastery
← Practice
Longest Consecutive Sequencemedium

Longest Consecutive Sequence

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement the O(n) hash-set solution to Longest Consecutive Sequence -- the classic case where sorting FEELS natural but is actually the wrong complexity, and a hash set achieves true O(n).

Related Skills

Task

Implement longest_consecutive(nums): put every number in a set; for each number that is the START of a run (i.e. number-1 is NOT in the set), count forward (number+1, number+2, ...) to find that run's length, and track the best.

Function Signature

longest_consecutive(nums: list[int]) -> int

Examples

Example 1: Scattered Input
Input: nums = [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The run 1,2,3,4
Example 2: Longer Run With a Duplicate
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output: 9
Explanation: The run 0 through 8 (the duplicate 0 does not extend it further)

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Must run in O(n) time -- sorting first (O(n log n)) does not satisfy the intended solution, even though it would give a correct answer.
  • An empty list has longest-consecutive length 0.
Python3Saved ✓
def longest_consecutive(nums: list[int]) -> int:
"""Return the length of the longest run of consecutive integers
present in nums (in any order in the input). Must run in O(n) time
(no sorting)."""
# Your implementation here
pass

Case 1: Scattered Input
Input: nums = [100, 4, 200, 1, 3, 2]
Expected: 4
Case 2: Longer Run With a Duplicate
Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Expected: 9