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.
- Place every number from the array into a Set for instant lookups.
- Iterate through the set:
- For each number, check if it is an Anchor (is
num - 1missing 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.
- For each number, check if it is an Anchor (is
- Record the length of every chain you find.
- Print the maximum length discovered.
01EXAMPLE 1
Input
[100, 4, 200, 1, 3, 2]Output
4Explanation: Streak: 1, 2, 3, 4.
Constraints
- Solve in O(n) time (Crucial: sorting is too slow at O(n log n)).
ArraysHashingAlgorithms
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[100,4,200,1,3,2]
Expected Output
4
Click RUN to test your solution