⬅ Previous Topic
Leaders in an ArrayNext Topic ⮕
Count Subarrays with Given Sum⬅ Previous Topic
Leaders in an ArrayNext Topic ⮕
Count Subarrays with Given SumTopic Contents
Given an unsorted array of integers, your task is to find the length of the longest sequence of consecutive numbers that appear in the array.
If the array is empty, return 0
.
arr
of integers.HashSet
for constant-time lookups.max_length = 0
.num
in arr
:num - 1
is not in the set (meaning num
is the start of a new sequence).current_length = 1
and incrementally check for num + 1, num + 2, ...
while they exist in the set, incrementing current_length
.max_length
with the maximum of max_length
and current_length
.max_length
.def longest_consecutive_sequence(arr):
num_set = set(arr)
max_length = 0
for num in arr:
if num - 1 not in num_set:
current = num
length = 1
while current + 1 in num_set:
current += 1
length += 1
max_length = max(max_length, length)
return max_length
# Sample Input
arr = [100, 4, 200, 1, 3, 2]
print("Longest Consecutive Sequence Length:", longest_consecutive_sequence(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In the best case, each element is checked only once, and very few sequences are formed. The HashSet operations are constant time on average. |
Average Case | O(n) | Each number is visited once when building the set and at most once again when scanning for sequence starts, resulting in linear time. |
Average Case | O(n) | Even in the worst case, each element is processed at most twice—once during insertion and once during sequence scanning. So time remains linear. |
O(n)
Explanation: A HashSet is used to store all unique elements of the array for quick lookups, which requires linear space in terms of the input size.
⬅ Previous Topic
Leaders in an ArrayNext Topic ⮕
Count Subarrays with Given SumYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.