Longest Consecutive Sequence
Updated
Problem statement
You are given an array of integers nums in no particular order. A consecutive sequence is a group of values where each value is exactly 1 more than the one before it, such as 4, 5, 6, 7.
Return the length of the longest consecutive sequence you can build from the values in nums. The values do not have to be next to each other in the array. A value that appears more than once still counts only once.
If nums is empty, return 0.
Aim for a solution that runs in O(n) time, where n is the length of nums.
Function
longestConsecutive(nums: int[]) → intExamples
Example 1
nums = [10,5,12,3,4,11,2]return = 4The values 2, 3, 4, 5 form a consecutive sequence of length 4. The values 10, 11, 12 form another one of length 3. The longer one has length 4.
Example 2
nums = [7,7,8,6,8]return = 3The different values are 6, 7 and 8. Together they form 6, 7, 8, so the answer is 3. The repeated 7 and 8 do not make the sequence longer.
Example 3
nums = []return = 0There are no values, so the longest sequence has length 0.
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
More JP Morgan Chase interview questions
- Maximize Binary XOR with a Set-Bit LimitPHONE SCREEN · Seen Oct 2026
- Top K Frequent Values Across Key-Partitioned ShardsPHONE SCREEN · Seen Sep 2026
- Best Time to Buy and Sell StockPHONE SCREEN · Seen Aug 2026
- All Index Pairs Sum to KPHONE SCREEN · Seen Aug 2026
- LFU CacheONSITE INTERVIEW · Seen Nov 2026
- LRU CacheONSITE INTERVIEW · Seen Nov 2026
- Find Total CostOA · Seen Oct 2026
- Minimum Meeting RoomsOA · Seen Oct 2026
- Count Dropped RequestsOA · Seen Oct 2026
- Maximize Minimum Deployment DifficultyOA · Seen Oct 2026
Similar questions at other companies
- Filter, Sort, and Deduplicate Scheduled TasksRippling · PHONE SCREEN · ONSITE INTERVIEWRippling interview questions
- Top K Frequent Elements with a Recency TiebreakSwiggy · PHONE SCREEN
- Pins Violation Log QueriesPinterest · PHONE SCREENPinterest interview questions
- Group AnagramsWorkday · PHONE SCREEN
- Build a Task and Subtask HierarchyStripe · PHONE SCREENStripe interview questions
- Find All Points Within a RadiusGoogle · PHONE SCREENGoogle interview questions
- Resource Reconciler: Plan and Apply CreatesPerplexity AI · PHONE SCREENPerplexity AI interview questions
- Top K Frequent ElementsAmazon · OA · PHONE SCREEN
- Build a Pivot Table with TotalsSigma Computing · PHONE SCREEN
- Group AnagramsEPAM · PHONE SCREENEPAM interview questions
JP Morgan Chase interview experiences
- JPMorgan Quant Stats Superdays: 3 Experiences (Part 3 of 3)
- JPMorgan Quant Modeling Superdays: 7 Experiences (Part 2 of 3)
- JPMorgan Quant Intern Superday: 19 Experiences (Part 1 of 3)
- JP Morgan Chase Data and AI Intern Superday: 11 Experiences
- JPMorgan Code for Good India 2024: 6 Experiences (Part 5 of 5)
- JPMorgan Code for Good India: 10 Experiences (Part 4 of 5)