Longest Consecutive Sequence
You get an unsorted array of numbers. Find the length of the longest chain of numbers that follow each other, x, x + 1, x + 2 and so on; where they stand in the array does not matter. Our example: [20, 4, 21, 2, 1, 3, 15] — the answer is 4: 1, 2, 3, 4.
- input
nums: an array of integers, in any order, repeats allowed.- returns
- The length of the longest run of consecutive integers
x, x + 1, …, x + kthat are all innums;0for an empty array. - constraints
- 0 ≤ nums.length ≤ 2000
- −10⁹ ≤ nums[i] ≤ 10⁹
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @return {number}
*/
function longestConsecutive(nums) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more hash map problems
- 1Two SumEasysolve
- 217Contains DuplicateEasysolve
- 242Valid AnagramEasysolve
- 169Majority ElementEasysolve
- 383Ransom NoteEasysolve
- 205Isomorphic StringsEasysolve
- 290Word PatternEasysolve
- 219Contains Duplicate IIEasysolve
- 49Group AnagramsMediumsolve
- 36Valid SudokuMediumsolve
- 138Copy List with Random PointerMediumsolve
- 149Max Points on a LineHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.