![]() |
VOOZH | about |
Given an arr[] of integers and a positive integer k, find the longest subarray's length with the sum of the elements divisible by k.
Examples:
Input: arr[] = [2, 7, 6, 1, 4, 5], k = 3
Output: 4
Explanation: The subarray [7, 6, 1, 4] has sum = 18, which is divisible by 3.Input: arr[] = [-2, 2, -5, 12, -11, -1, 7], k = 3
Output: 5
Explanation: The subarray [2, -5, 12, -11, -1], has sum = -3, which is divisible by 3.Input: arr[] = [1, 2, -2], k = 5
Output: 2
Explanation: The subarray is [2, -2] with sum = 0, which is divisible by 5.
Table of Content
Consider all the subarray sums using two nested for loops and return the length of the longest subarray with a sum divisible by k. To avoid overflow while computing the sum of the subarray, we can keep track of (subarray sum % k) and if (subarray sum % k) results to 0, we can use its length to find the longest subarray divisible by k.
4
The idea is to use Prefix Sum Technique along with Hashing. On observing carefully, we can say that if a subarray arr[iā¦j] has sum divisible by k, then (prefix sum[i] % k) will be equal to the (prefix sum[j] % k). So, we can iterate over arr[] while maintaining a hash map or dictionary to keep track of the first occurrence of of (prefix sum % k) at each index. For each index i, the longest subarray ending at i and having sum divisible by k will be equal to i - first occurrence of (prefix sum[i] % k).
4