The goal is to find the longest consecutive sequence of integers than can be selected in the list given in argument. This list is unsorted and the selection has no rule. The algorithm must have a temporal complexity of O(n).
The idea of the algorithm is to use a set:
def longestConsecutive(nums: List[int]) -> int:
# Cast nums in set as we do not care about duplicate values and set average access time is O(1); set_seen keeps already seen numbers
set_nums, set_seen = set(nums), set()
max_count = 0
for i in set_nums:
# Do not check again if i has already been seen; that means that a sequence starting with a smaller i has been checked
if i not in set_seen:
j = 0
while i + j in set_nums:
# Add i+j in set_seen in order to not check the sequence starting at i+j (shorter sequence than current one)
set_seen.add(i + j)
j += 1
max_count = max(max_count, j)
return(max_count)