LeetCode 0128. Longest Consecutive Sequence Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0128. Longest Consecutive Sequence

Description

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.

 

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

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

Example 3:

Input: nums = [1,0,1,2]
Output: 3

 

Constraints:

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

Solutions

Solution 1: Hash Table

We can use a hash table s to store all the elements in the array, a variable ans to record the length of the longest consecutive sequence, and a hash table d to record the length of the consecutive sequence each element x belongs to.

Next, we iterate through each element x in the array, using a temporary variable y to record the maximum value of the current consecutive sequence, initially y = x. Then, we continuously try to match y+1, y+2, y+3, \dots until we can no longer match. During this process, we remove the matched elements from the hash table s. The length of the consecutive sequence that the current element x belongs to is d[x] = d[y] + y - x, and then we update the answer ans = max(ans, d[x]).

After the iteration, we return the answer ans.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) ans = 0 d = defaultdict(int) for x in nums: y = x while y in s: s.remove(y) y += 1 d[x] = d[y] + y - x ans = max(ans, d[x]) return ans(code-box)

Solution 2: Hash Table (Optimization)

Similar to Solution 1, we use a hash table s to store all the elements in the array and a variable ans to record the length of the longest consecutive sequence. However, we no longer use a hash table d to record the length of the consecutive sequence each element x belongs to. During the iteration, we skip elements where x-1 is also in the hash table s. If x-1 is in the hash table s, then x is definitely not the start of a consecutive sequence, so we can directly skip x.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.

PythonJavaC++GoTypeScriptRustJavaScript
class Solution: def longestConsecutive(self, nums: List[int]) -> int: s = set(nums) ans = 0 for x in s: if x - 1 not in s: y = x + 1 while y in s: y += 1 ans = max(ans, y - x) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !