Problem - Leetcode
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
Constraints:
0 <= nums.length <= 10<sup>5</sup>
-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup>
Answer-1 in Golang
func longestConsecutive(nums []int) int {
set := make(map[int]bool)
for _, num := range nums {
set[num] = true
}
res := 0
for _, num := range nums {
if set[num-1] {
continue
}
sequence := 1
temp := num + 1
for set[temp] {
sequence++
temp++
}
if sequence > res {
res = sequence
}
}
return res
}
This code defines a function longestConsecutive
that takes an array of integers nums
as input and returns the length of the longest consecutive subsequence within the array. Let's break down the code step by step:
Function
longestConsecutive
:- This function calculates the length of the longest consecutive subsequence in the input array.
Creating a Set:
A set (
map[int]bool
) namedset
is created to store unique integers.The first loop iterates through the
nums
array and inserts each element into theset
with a value oftrue
. This ensures that duplicates are removed and we have a set of unique values.
Initializing Result Variable:
- The variable
res
is initialized to store the result, which will be the length of the longest consecutive subsequence.
- The variable
Finding Longest Consecutive Subsequence:
The second loop iterates through the
nums
array again.For each element
num
, it checks ifnum-1
is present in theset
. If it is, this meansnum
is not the starting point of a consecutive sequence, so the loop continues to the next iteration.If
num-1
is not present in theset
, it meansnum
is the potential starting point of a consecutive sequence.The variable
sequence
is initialized to 1, representing the length of the sequence that starts atnum
.The variable
temp
is initialized tonum + 1
, and the loop searches for consecutive elements in theset
by checking iftemp
exists.While consecutive elements are found in the
set
, thesequence
counter is incremented, andtemp
is incremented to move to the next element.After the loop, the length of the consecutive subsequence starting at
num
is stored in thesequence
variable.
Updating the Result:
- If the
sequence
length is greater than the current value ofres
, the value ofres
is updated with the length of the current sequence. This ensures that the maximum sequence length is tracked.
- If the
Returning the Result:
- After the loop completes, the function returns the value of
res
, which represents the length of the longest consecutive subsequence.
- After the loop completes, the function returns the value of
In summary, this code uses a set to efficiently store unique integers from the input array. Then, it iterates through the array again, checking for each element whether it's the starting point of a consecutive sequence. If it is, the code counts the length of that consecutive sequence and updates the result if a longer sequence is found. This approach has a time complexity of O(n) due to the two loops, where n is the length of the input array.
Answer-2 Top Runtime in Golang
func getMax(a, b int) int {
if a > b {
return a
}
return b
}
func longestConsecutive(nums []int) int {
if len(nums) == 0 {
return 0
}
sort.Ints(nums)
cur, maxVal := 1, 1
for i := 1 ; i < len(nums) ; i ++ {
if nums[i-1]+1 == nums[i] {
cur++
} else if nums[i-1] == nums[i] {
continue
} else {
cur = 1
}
maxVal = getMax(maxVal, cur)
}
return maxVal
}
This code defines a function longestConsecutive
that takes an array of integers nums
as input and returns the length of the longest consecutive subsequence within the array. Let's break down the code step by step:
Function Definitions for
getMax
:- A utility function
getMax
is defined to return the maximum of two integer values.
- A utility function
Function
longestConsecutive
:- This is the main function that calculates the length of the longest consecutive subsequence in the input array.
Handling Empty Array:
- The function first checks if the length of the
nums
array is zero. If it is, there are no elements, and the function immediately returns 0.
- The function first checks if the length of the
Sorting the Input Array:
- The
nums
array is sorted in ascending order using thesort.Ints
function. Sorting is performed to make consecutive elements adjacent to each other.
- The
Initializing Variables:
The variables
cur
andmaxVal
are initialized to 1.cur
will keep track of the length of the current consecutive subsequence being processed.maxVal
will store the maximum length of consecutive subsequences encountered.
Iterating Through the Sorted Array:
A loop starts from the second element (index 1) and iterates through the
nums
array.For each iteration, the code checks three conditions:
If the previous element (
nums[i-1]
) plus 1 is equal to the current element (nums[i]
), it means the current element is part of a consecutive sequence. In this case, thecur
counter is incremented.If the previous element is equal to the current element, it means the current element is a duplicate. The loop continues to the next iteration.
If neither of the above conditions is satisfied, it means the current element breaks the consecutive sequence. The
cur
counter is reset to 1.
Updating
maxVal
:- After evaluating the conditions for each element, the
maxVal
is updated using thegetMax
utility function. It compares the current value ofmaxVal
with the current value ofcur
and updatesmaxVal
ifcur
is greater.
- After evaluating the conditions for each element, the
Returning the Result:
- After processing all elements, the function returns the value of
maxVal
, which represents the length of the longest consecutive subsequence in the input array.
- After processing all elements, the function returns the value of
In summary, this code calculates the length of the longest consecutive subsequence by sorting the array and then iterating through it. It keeps track of the current consecutive sequence length and updates the maximum length encountered. The approach has a time complexity of O(n * log n) due to the sorting step, where n is the length of the input array. The subsequent loop has a time complexity of O(n).
Answer-3 Top Memory in Golang
func longestConsecutive(nums []int) int {
if len(nums) == 0 { return 0 }
sort.Slice(nums, func (i, j int) bool {
return nums[i] < nums[j]
})
longest := 1
current := 1
for i := 1; i < len(nums); i++ {
if nums[i] == nums[i-1] + 1 {
current++
} else if nums[i] != nums[i -1] {
current = 1
}
if current > longest {
longest = current
}
}
return longest
}
This code defines a function longestConsecutive
that takes an array of integers nums
as input and returns the length of the longest consecutive subsequence within the array. Let's break down the code step by step:
Function
longestConsecutive
:- This is the main function that calculates the length of the longest consecutive subsequence in the input array.
Handling Empty Array:
- The function first checks if the length of the
nums
array is zero. If it is, there are no elements, and the function immediately returns 0.
- The function first checks if the length of the
Sorting the Input Array:
- The
nums
array is sorted in ascending order using thesort.Slice
function. Sorting is performed using a custom comparison function that returnstrue
ifnums[i]
is less thannums[j]
. Sorting is done to ensure that consecutive elements are adjacent to each other after sorting.
- The
Initializing Variables:
The variables
longest
andcurrent
are initialized to 1.longest
will store the length of the longest consecutive subsequence encountered.current
will keep track of the length of the current consecutive subsequence being processed.
Iterating Through the Sorted Array:
A loop starts from the second element (index 1) and iterates through the sorted
nums
array.For each iteration, the code checks two conditions:
If the current element (
nums[i]
) is equal to the previous element (nums[i-1]
) plus 1, it means the current element is part of a consecutive sequence. In this case, thecurrent
counter is incremented.If the current element is not equal to the previous element, it means the current element is not part of the current consecutive sequence. The
current
counter is reset to 1.
The code also ensures that if consecutive elements are duplicates (have the same value), they do not affect the sequence length.
Updating
longest
:- After evaluating the conditions for each element, the
longest
length is updated if thecurrent
length is greater.
- After evaluating the conditions for each element, the
Returning the Result:
- After processing all elements, the function returns the value of
longest
, which represents the length of the longest consecutive subsequence in the input array.
- After processing all elements, the function returns the value of
In summary, this code calculates the length of the longest consecutive subsequence by sorting the array and then iterating through it. It keeps track of the current consecutive sequence length and updates the maximum length encountered. The approach has a time complexity of O(n * log n) due to the sorting step, where n is the length of the input array. The subsequent loop has a time complexity of O(n). This code uses a more concise approach compared to the previous one, achieving the same result.