1-liner in Python using Counter


  • 0
    O
    class Solution(object):
        def intersect(self, nums1, nums2):
            return list(itertools.chain.from_iterable([k]*v for k,v in (collections.Counter(nums1)&collections.Counter(nums2)).iteritems()))
    

    Which is equivalent to:

    class Solution(object):
        def intersect(self, nums1, nums2):
            cnt = collections.Counter(nums1) & collections.Counter(nums2)
            return list(itertools.chain.from_iterable([k]*v for k,v in cnt.iteritems()))
    

    The & operator of Counter is very handy here.

    itertools.chain is there to concat lists efficiently. A shorter version is using sum, but the time complexity is not optimal.


Log in to reply
 

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