Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. def longest_consecutive_subsequence(input_list):
  2. """
  3. Gets the longest sequential (consecutive set of numbers from the given unsorted list.
  4.  
  5. Time complexity is O(n) and space complexity is O(n).
  6.  
  7. This design uses Python's `range()` function to generate the list of sequential numbers. To accomplish this,
  8. we iterate through the input list to find the least starting number and the number of sequential numbers.
  9.  
  10. It works on all integers.
  11.  
  12. :param input_list: given unsorted list of integers (positive and/or negative).
  13. :return: returns a list of the longest sequential numbers.
  14. """
  15.  
  16. # Create a dictionary where number: visited.
  17. # Value of 1 means the number has been visited (processed).
  18. nums = {num: 0 for num in input_list} # O(n)
  19.  
  20. current_start = None
  21. current_count = 0
  22. longest_start = None
  23. longest_count = 0
  24.  
  25. for num in input_list: # O(n)
  26. current_count = 1
  27. current_start = num
  28. nums[num] = -1
  29.  
  30. # Check sequential n + 1.
  31. current = num + 1
  32. while current in nums and nums[current] == 0:
  33. current_count += 1
  34. nums[current] = 1 # Mark that this number has been visited.
  35. current += 1
  36.  
  37. # Check sequential n - 1.
  38. current = num - 1
  39. while current in nums and nums[current] == 0:
  40. current_start = current
  41. current_count += 1
  42. nums[current] = 1 # Mark that this number has been visited.
  43. current -= 1
  44.  
  45. if current_count == longest_count and current_start > longest_start:
  46.  
  47. continue
  48.  
  49. if current_count >= longest_count:
  50. longest_start = current_start
  51. longest_count = current_count
  52.  
  53. return [num for num in range(longest_start, longest_start + longest_count)]
  54.  
  55. if __name__ == '__main__':
  56. test_case = [
  57. [[5, 4, 7, 10, 1, 3, 55, 2], [1, 2, 3, 4, 5]],
  58. [[2, 12, 9, 16, 10, 5, 3, 20, 25, 11, 1, 8, 6], [8, 9, 10, 11, 12]],
  59. [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],
  60. [[25, 35, 45, 12, 26, 36, 13, 24, 44, 23], [23, 24, 25, 26]],
  61. [[0, -1, -2, -3, -10, 20, 30, -4], [-4, -3, -2, -1, 0]]
  62. ]
  63.  
  64. for input, expected in test_case:
  65. actual = longest_consecutive_subsequence(input)
  66. if actual == expected:
  67. print("Passed")
  68. else:
  69. print("Failed. actual {} vs. expected {}".format(actual, expected)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement