128. Longest Consecutive Sequence Leetcode Solution

Longest Consecutive Sequence Leetcode Problem :

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

You must write an algorithm that runs in O(n) time.

jump game leetcode

Longest Consecutive Sequence Leetcode Solution :

Constraints :

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

Example 1:

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

Approach :

  1. insert all the nums elements in a set, now the set will contain all the unique elements in the array.
  2. now traverse the array nums.
  3. if there is any smaller elemets in the set from num[i], then continue because for the longest sequence we will have to start
    from the smallest element of the given sequence.
  4. if there is no any smaller element than nums[i] in the set, then starting from current element maitain a while loop until the next element is not present in the set. Now update the ans variable.
  5. finally we get the answer.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription