#974

Subarray Sums Divisible by K

Medium
ArrayHash TablePrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a prefix sum and a hash map to efficiently count the number of valid subarrays. By tracking the remainders of prefix sums, we can quickly determine how many previous sums can form a valid subarray with the current sum.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a hash map to store the frequency of remainders and a variable for the prefix sum.
  2. 2Step 2: Iterate through the array, updating the prefix sum and calculating the remainder when divided by k.
  3. 3Step 3: If the remainder is negative, adjust it to be positive by adding k.
  4. 4Step 4: Check if this remainder has been seen before in the hash map. If so, add its frequency to the count.
  5. 5Step 5: Increment the frequency of the current remainder in the hash map.
solution.py14 lines
1# Full working Python code
2
3def subarraySumDivisibleByK(nums, k):
4    count = 0
5    prefix_sum = 0
6    remainder_count = {0: 1}
7    for num in nums:
8        prefix_sum += num
9        remainder = prefix_sum % k
10        if remainder < 0:
11            remainder += k
12        count += remainder_count.get(remainder, 0)
13        remainder_count[remainder] = remainder_count.get(remainder, 0) + 1
14    return count

Complexity note: The optimal solution runs in linear time because we only make a single pass through the array while using a hash map to store remainders, leading to efficient lookups.

  • 1Using prefix sums allows us to efficiently calculate subarray sums without recalculating them multiple times.
  • 2Hash maps can be used to track the frequency of remainders, which helps in counting valid subarrays quickly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.