Tuesday, March 8, 2022

Leetcode discuss: 523. Continuous Subarray Sum

 March 8, 2022

Here is the link.


C# | Learn from failed test cases

March 7, 2022
Introduction
It is such great learning experience to learn those failed test cases. After a few iterations, I figured out working solution

learn from failed test cases

  1. {23, 2, 6, 4, 7], k = 13
    a hashset should save residue, not k - residue
  2. [23,2,4,6,6], k = 7, should consider residue == 0 case
  3. [1,0], k = 2, true, expected: false - at least two numbers, so [0] subarray only contains one number.

The following C# code passes online judge.

public class Solution {
    public bool CheckSubarraySum(int[] nums, int k) {
        if (nums == null || nums.Length < 2 || k <= 0)
                return false;

            var prefixSum = 0;
            var length = nums.Length;
            var hashSet = new HashSet<int>();
            
            // {1, 0}, k = 2
            var saved = new int[length];

            for (int i = 0; i < length; i++)
            {
                prefixSum += nums[i];
                var residue = prefixSum % k;

                if (i > 1)
                {
                    hashSet.Add(saved[i - 2]);
                }

                if ((i>= 1 && residue == 0) || hashSet.Contains(residue))
                {
                    return true;
                }
                else
                {
                    saved[i] = residue;                    
                }               
            }

            return false;
    }
}


No comments:

Post a Comment