For example, given input arr = [4,5,0,-2,-3,1], k = 5, there are 7 subarrays with a sum divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]. The shortest one is either [5] or [0], both are correct. If there are no answers return an empty array.
This question is similar to leetcode no. 974 but I can't figure out how to apply the same algorithm to this (that one doesn't really account for the length of subarrays). Can someone help (preferably in python). Thank you!
Track the cumulative sums mod k in a map, with the cum_sums mod k as keys and the most recent index as values. Prior to updating the map for each index, first check if that key already exists. If it does, you have a contiguous subsequence divisible by k, and can calculate the length from the indices. Keep track of the min length.
Ruby code