Concise Python solution using set beats 96%


  • 0
    S

    All we need is a pair of sum(nums[1...m]) % k and sum(nums[1...n]) % k being the same with n > m + 1, so I use a set to record all possible sum(nums[1...m]), and withhold the previous cumulated sum p until the next round.

    Trick to made the code shorter (but not necessarily faster) is to re-define the modulo function to handle edge cases (k <= 0).

    class Solution(object):
        def checkSubarraySum(self, nums, k):
            st = set()
            p = s = 0
            for i in xrange(0, len(nums)):
                s = (s + nums[i]) if k == 0 else (s + nums[i]) % abs(k)
                if s in st: return True
                st.add(p)
                p = s
            return False
    

Log in to reply
 

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