Created
January 24, 2019 16:53
-
-
Save flavienbwk/6021a4b7674fcaf1743c2beae9297a35 to your computer and use it in GitHub Desktop.
Coding interview problem : find the longest consecutive sequence in a sequence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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