128. Longest Consecutive Sequence
Asked at 38Amazon71Google71Bloomberg71Microsoft63Meta56Apple53tcs57Infosys45Wissen Technology100Paytm85Okta81Walmart Labs71BitGo68TikTok67Myntra64Arcesium61Swiggy59Oracle55Nvidia55eBay53PhonePe53Tesla52PayPal51EPAM Systems51IBM50Deloitte50Cognizant48Adobe44Lyft43Intuit43Zoho42Goldman Sachs40DE Shaw38Cisco37Atlassian34Uber30Salesforce28LinkedIn20
Problem
Given an unsorted integer array nums, return the length of the longest run of consecutive integers (like 1, 2, 3, 4) whose values all appear in nums. The values don't need to be adjacent in the array.
Example: [100,4,200,1,3,2] → 4 (the run 1, 2, 3, 4)
Constraints: n ≤ 10⁵; must run in O(n).
Put everything in a set. Only start counting from numbers that begin a run (x - 1 not in set), then walk x+1, x+2, …. Each number is visited at most twice → O(n).
set {100, 4, 200, 1, 3, 2}
1 (0 missing -> start) 1,2,3,4 -> length 4
100 (99 missing -> start) 100 -> length 1
2 (1 present -> skip, not a start)
Complexity: O(n) time, O(n) space.
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x starts a run
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return best
assert Solution().longestConsecutive([100, 4, 200, 1, 3, 2]) == 4
assert Solution().longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]) == 9
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> s = new HashSet<>();
for (int x : nums) s.add(x);
int best = 0;
for (int x : s) {
if (s.contains(x - 1)) continue; // not the start of a run
int y = x;
while (s.contains(y + 1)) y++;
best = Math.max(best, y - x + 1);
}
return best;
}
}
func longestConsecutive(nums []int) int {
set := map[int]bool{}
for _, x := range nums {
set[x] = true
}
best := 0
for x := range set {
if !set[x-1] { // x starts a run
y := x
for set[y+1] {
y++
}
best = max(best, y-x+1)
}
}
return best
}