Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

128. Longest Consecutive Sequence #4

Merged
merged 1 commit into from
Jul 10, 2024
Merged

128. Longest Consecutive Sequence #4

merged 1 commit into from
Jul 10, 2024

Conversation

stada526
Copy link
Owner

Problem Link

https://leetcode.com/problems/longest-consecutive-sequence/description/

Solution

A solution that springs to mind is to sort the input nums in ascending order and traverse the sorted array.
During the traversal, if the adjacent elements are consecutive, increment a counter.
If the current element is not consecutive to the previous element, reset the counter to 0 and start again.
This approach operations in O(n * log n ) time complexity, but we're supposed to solve this problem in O(n).

For a more efficient approach, consider traversing the unsorted nums directly.
In each iteration, if the current element is the start of a sequence, determine how many consecutive elements are contained in nums staring from that element.
An element is considered the start of a sequence if the value element -1 is not present in nume.
To do this with a time complexity of O(n), use a hash set to store all elements of nums

@stada526 stada526 merged commit e2fa6cf into main Jul 10, 2024
1 check passed
@stada526 stada526 deleted the f/128 branch July 10, 2024 23:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant