C# - O(n) time - O(k) space - Hashtable


  • 0
        public bool CheckSubarraySum(int[] nums, int k) 
        {
            Dictionary<int,int> map = new Dictionary<int,int>();
            map[0] = -1;
            int sum = 0;
            for (int i = 0; i < nums.Length; i++)
            {
                sum += nums[i];
                if (sum == 0 && i >= 1) return true;
                if (k != 0)
                {
                    int mod = sum % k;
                    if (map.ContainsKey(mod))
                    {
                        if (i - map[mod] >= 2) return true;
                    }
                    else
                    {
                        map[mod] = i;
                    }       
                }
                 
            }
            
            return false;
        }
    

Log in to reply
 

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