This is a Leetcode problem -
Given an unsorted array of integers, find the length of the longest consecutive elements' sequence.
Your algorithm should run in \$O(n)\$ complexity.
Input: [100, 4, 200, 1, 3, 2] Output: 4 # Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Here is my solution to this challenge -
def longestConsecutive(nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 nums = list(dict.fromkeys(nums)) nums.sort() count = 1 longest_streak =  for index, value in enumerate(nums): if index + 1 >= len(nums): break if nums[index + 1] == value + 1: count += 1 longest_streak.append(count) else: count = 1 if not longest_streak: return count return max(longest_streak)
Here is my Leetcode result -
So, I would like to know whether I could make this program faster and more efficient.
NOTE - Though my solution got accepted, I really have no idea about the time complexity of my program. Maybe someone could cover that too?