code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

128 Longest Consecutive Sequence

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const longestConsecutiveSequence = nums => {
  let set = new Set(nums)
  let counter = 0
  let max = 0
  for (let i = 0; i < nums.length; i++) {
    if (!set.has(nums[i] - 1)) {
      let current = nums[i]
      while (set.has(current++)) {
        counter++
        max = Math.max(counter, max)
      }
      counter = 0
    }
  }
  return max
}

console.log(longestConsecutiveSequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]))

Created 2023-05-20T17:20:34+01:00 · Edit