SIMPLE TO UNDERSTAND Python solution O(N) time and space, uses sets


  • 0
    class Solution(object):
        def longestConsecutive(self, nums):
            
            def _calc_longest(elem, set_nums):
                length, start = 0, elem
                while start in set_nums:
                    set_nums.discard(start)
                    length += 1
                    start += 1
                start = elem - 1
                while start in set_nums:
                    set_nums.discard(start)
                    length += 1
                    start -= 1
                return length
            
            
            set_nums = set(nums)
            maximum = 1
            for elem in nums:
                if not len(set_nums): break
                maximum = max(maximum, _calc_longest(elem, set_nums))
            return maximum

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.