Consecutive Chain

HardAcc. 64.5%
+50 XP 30

The Anchor Chain (Consecutive sequence)

Imagine you have a bag of unsorted numbers and you want to find the longest "chain" of consecutive values (e.g., 1, 2, 3, 4). Usually, you would sort them first ($O(N log N)$), but we need to do this in a single lightning-fast pass ($O(N)$). We can do this by using a Set to instantly check for the existence of neighbors and only starting a count from an "Anchor"—the smallest number in a potential chain.

The Assignment

Your mission is to find the longest chain length. Your function receives an array nums.

  1. Place every number from the array into a Set for instant lookups.
  2. Iterate through the set:
    • For each number, check if it is an Anchor (is num - 1 missing from the set?).
    • If it is an Anchor, start a "Chain Count." Keep looking for num + 1, num + 2, etc., as long as they exist in the set.
  3. Record the length of every chain you find.
  4. Print the maximum length discovered.

01EXAMPLE 1

Input[100, 4, 200, 1, 3, 2]
Output4

Explanation: Streak: 1, 2, 3, 4.

Constraints

  • Solve in O(n) time (Crucial: sorting is too slow at O(n log n)).
ArraysHashingAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

nums[100,4,200,1,3,2]

Expected Output

4

Click RUN to test your solution