Longest Consecutive Sequence in an Array

Hashing FAQs Hard
  • This problem can be applied in the development of streaming multimedia platforms, for example, Netflix or YouTube
  • These platforms need to correctly sequence video packets, which could arrive out of order, to provide a seamless streaming experience
  • Understanding how to find/integrate sequences of consecutive numbers can therefore be crucial for designing the algorithms to handle this task

Given an array nums of n integers, return the length of the longest sequence of consecutive integers. The integers in this sequence can appear in any order.

Examples:

Input: nums = [100, 4, 200, 1, 3, 2]

Output: 4

Explanation: The longest sequence of consecutive elements in the array is [1, 2, 3, 4], which has a length of 4. This sequence can be formed regardless of the initial order of the elements in the array.

Input: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]

Output: 9

Explanation: The longest sequence of consecutive elements in the array is [0, 1, 2, 3, 4, 5, 6, 7, 8], which has a length of 9. 

Input: nums = [1, 9, 3, 10, 4, 20, 2]

Constraints

  •      1 <= nums.length <= 105
  •      -109 <= nums[i] <= 109

Hints

  • Use a hash set to store all elements of the array. Iterate through the array, and for each element, check if it is the start of a sequence by ensuring that num−1 is not in the set.
  • For each starting number, count the length of the consecutive sequence by checking for num+1, num+2, etc., in the set. Maintain a variable to store the length of the longest sequence encountered during the traversal.

Company Tags

Zynga DoorDash Western Digital Unity Technologies Ernst & Young eBay Riot Games Bloomberg GE Healthcare HashiCorp Micron Technology Qualcomm Texas Instruments Docker PwC Swiggy PayPal JPMorgan Chase Ubisoft Activision Blizzard Teladoc Health NVIDIA Instacart Boston Consulting Group Rakuten Google Microsoft Amazon Meta Apple Netflix Adobe