Created
May 28, 2025 22:30
-
-
Save GopinathMR/91d2f68dd22e0fa675b69611830d94f9 to your computer and use it in GitHub Desktop.
leetcode 523 : handling zeros correctly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* Default solution you find in youtube won't work for [4, 1, 0] , k = 3. So, we need to add extra check for | |
* this corner case. | |
* Test cases 4, 5 and 6 pose interesting scenario because of 0s. | |
*/ | |
public class Solution { | |
/** | |
* Placeholder for the actual test method. | |
* | |
* @param nums input array | |
* @param k integer k | |
* @return true if a continuous subarray sum is a multiple of k, false otherwise | |
*/ | |
public boolean checkSubarraySum(int[] nums, int k) { | |
Map<Integer, Integer> indexMap = new HashMap<>(); | |
int sum = 0; | |
boolean prevZero = false; // to handle corner case scenario with zeros | |
for (int index = 0; index < nums.length; ++index) { | |
sum = (sum + nums[index]); | |
if (indexMap.containsKey(sum % k)) { | |
if (nums[index] == 0 && !prevZero) { | |
prevZero = (nums[index] == 0) ? true : false; | |
continue; | |
} | |
return true; | |
} else { | |
indexMap.put(sum % k, index); | |
} | |
prevZero = (nums[index] == 0) ? true : false; | |
} | |
return false; | |
} | |
public static void main(String[] args) { | |
Solution solution = new Solution(); | |
int[][] testInputs = { | |
{ 23, 2, 4, 6, 7 }, // Example 1 | |
{ 23, 2, 6, 4, 7 }, // Example 2 | |
{ 23, 2, 6, 4, 7 }, // Example 3 | |
{ 1, 0 }, // Example 4 | |
{ 0, 0 }, // Example 5 | |
{ 5, 0, 0, 0 }, // Additional test case | |
{ 1, 2, 3 }, // Additional test case | |
{ 1, 2, 3, 4, 5 }, // Additional test case | |
{ 0, 1, 0, 3, 0, 4, 0, 4, 0 } // Additional test case | |
}; | |
int[] kValues = { 6, 6, 13, 2, 1, 3, 5, 9, 5 }; | |
boolean[] expectedResults = { true, true, false, false, true, true, true, true, false }; | |
for (int i = 0; i < testInputs.length; i++) { | |
try { | |
boolean result = solution.checkSubarraySum(testInputs[i], kValues[i]); | |
System.out.printf("Test case %d:%n", i + 1); | |
System.out.printf("Input: nums = %s, k = %d%n", Arrays.toString(testInputs[i]), kValues[i]); | |
System.out.printf("Expected: %b%n", expectedResults[i]); | |
System.out.printf("Got: %b%n", result); | |
System.out.printf("Test %s%n%n", result == expectedResults[i] ? "PASSED" : "FAILED"); | |
} catch (UnsupportedOperationException e) { | |
System.out.printf("Test case %d: Not implemented\n", i + 1); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment