Skip to content

Instantly share code, notes, and snippets.

@flavienbwk
Created January 24, 2019 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flavienbwk/6021a4b7674fcaf1743c2beae9297a35 to your computer and use it in GitHub Desktop.
Save flavienbwk/6021a4b7674fcaf1743c2beae9297a35 to your computer and use it in GitHub Desktop.
Coding interview problem : find the longest consecutive sequence in a sequence.
# You have to return the longest consecutive sequence of numbers in an array.
# If the input is [2, 1, 6, 9, 4, 3], the output must be [1, 2, 3, 4]
# O(n)
def longestSequence(sequence):
hashtable = {}
longest = []
for i in range(0, len(sequence)):
hashtable[sequence[i]] = True
for number in hashtable:
if number - 1 not in hashtable: # If the current number is a minimum
current = number
longest_tmp = []
while (current in hashtable): # While there's a number following the current one
longest_tmp.append(current)
current += 1
if len(longest_tmp) > len(longest):
longest = longest_tmp
return longest
print longestSequence([2, 1, 6, 9, 4, 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment