Advertisement
smj007

Untitled

Jul 31st, 2023
1,094
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. """
  2. O(n)
  3.  
  4. Hash the array. Iterate over the hashtable and start counting only from those numbers whose preceding number does not exist in hashtable and then keep checking and counting after that for building the sequence.
  5.  
  6. Although the time complexity appears to be quadratic due to the while loop nested within the for loop, closer inspection reveals it to be linear. Because the while loop is reached only when currentNum marks the beginning of a sequence (i.e. currentNum-1 is not present in nums), the while loop can only run for nnn iterations throughout the entire runtime of the algorithm. This means that despite looking like O(n⋅n) complexity, the nested loops actually run in O(n+n) = O(n)O(n+n)=O(n) time. All other computations occur in constant time, so the overall runtime is linear.
  7. """
  8.  
  9. class Solution:
  10.     def longestConsecutive(self, nums: List[int]) -> int:
  11.        
  12.         if not len(nums):
  13.             return 0
  14.  
  15.         hashmap = set(nums)
  16.         longest_streak = float('-inf')
  17.  
  18.         for num in hashmap:
  19.             if num - 1 not in hashmap:
  20.                 streak_starting_here = 1
  21.                 current_num = num
  22.                 while(current_num+1 in hashmap):
  23.                     streak_starting_here+= 1
  24.                     current_num += 1
  25.  
  26.                 longest_streak = max(streak_starting_here, longest_streak)
  27.  
  28.         return longest_streak
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement