Longest Consecutive Sequence
Updated
Problem statement
Given an unsorted array of integers nums, return the length of the longest run of consecutive values.
A run of consecutive values is a set of numbers x, x + 1, x + 2, ..., x + k - 1 that all appear somewhere in nums. Its length is k. The numbers can be in any position in the array, and a value that appears more than once counts only once. If nums is empty, return 0.
Try to find an O(n) time solution, where n is the length of nums.
Function
longestConsecutive(nums: int[]) → intExamples
Example 1
nums = [100,4,200,1,3,2]return = 4The values 1, 2, 3, 4 all appear, so they form a run of length 4. 100 and 200 are runs of length 1. The longest run has length 4.
Example 2
nums = [0,3,7,2,5,8,4,6,0,1]return = 9The values 0 through 8 all appear, which is a run of length 9. The value 0 appears twice but counts once.
Example 3
nums = [9,1,4,7,3,-1,0,5,8,-1,6]return = 7The two longest runs that cannot grow are -1, 0, 1 (length 3) and 3, 4, 5, 6, 7, 8, 9 (length 7). The value -1 appears twice but counts once. 2 is missing, so the two runs do not join. The answer is 7.
Constraints
0 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9
More Kotak Mahindra Bank interview questions
- Longest Common PrefixPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Palindrome NumberPHONE SCREEN · Seen Nov 2026
- Validate Binary Search TreePHONE SCREEN · Seen Nov 2026
- Roman to IntegerPHONE SCREEN · ONSITE INTERVIEW · Seen Oct 2026
- Remove Duplicates From Sorted Array In PlacePHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
- Best Time to Buy and Sell StockONSITE INTERVIEW · Seen Nov 2026
- Best Time to Buy and Sell Stock IIONSITE INTERVIEW · Seen Nov 2026
- Maximum Non-Adjacent Coins in Two RowsONSITE INTERVIEW · Seen Oct 2026
- Search in Rotated Sorted ArrayONSITE INTERVIEW · Seen Oct 2026
- Find the Index of the First Occurrence in a StringONSITE INTERVIEW · Seen Oct 2026
Similar questions at other companies
- Insert Delete GetRandom O(1)Charta Health · PHONE SCREENCharta Health interview questions
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Longest Consecutive SequenceJP Morgan Chase · PHONE SCREENJP Morgan Chase interview questions
- Linked Merchants Within Two HopsStripe · PHONE SCREENStripe interview questions
- Logger Rate Limiter with Every-Arrival HistoryGoogle · PHONE SCREENGoogle interview questions
- Propagating Fraud DetectorAffirm · PHONE SCREEN · ONSITE INTERVIEWAffirm interview questions
- Top K Frequent Elements with a Recency TiebreakSwiggy · PHONE SCREEN
- Order and Batch Open-Close LifecycleHudson River Trading · PHONE SCREENHudson River Trading interview questions
- Pins Violation Log QueriesPinterest · PHONE SCREENPinterest interview questions
- Group AnagramsWorkday · PHONE SCREEN