Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Hash Map / Set Medium frequency Solution Available Practice Mode

Subarray Sum Divisible by K LeetCode Solution

Tags: #Array #Hash Table #Prefix Sum

Approach Summary

Prefix sum mod k. Two indices with the same running mod form a subarray divisible by k. Track mod frequencies in a HashMap.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Hash Map / Set Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Hash Map / Set pattern.

Framework: Hash Map / Set • Interview Prep: Tested at FAANG • Explore all Hash Map / Set problems & invariants →

How to Recognize This Pattern

  • "Subarrays divisible by k"
  • Prefix mod: same mod at two indices → divisible subarray between them

Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(k)

Tags

Array Hash Table Prefix Sum

Frequently Asked Questions

What is the optimal time and space complexity for Subarray Sum Divisible by K?
The optimal solution for Subarray Sum Divisible by K achieves O(n) runtime complexity and requires O(k) auxiliary space. Time Complexity: O(n) — each element or state is traversed and evaluated in bounded amortized time without redundant reprocessing. Space Complexity: O(k) — allocated for auxiliary tracking structures, recursion call stack, or state caches.
How do I identify that Subarray Sum Divisible by K requires the Hash Map / Set pattern?
In technical interviews, look for key problem signals: "Subarrays divisible by k"; Prefix mod: same mod at two indices → divisible subarray between them. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Hash Map / Set strategy.
What critical edge cases must be handled in Subarray Sum Divisible by K?
Essential edge cases to verify include: Key recognition trigger: "Subarrays divisible by k".; Constraint condition: Prefix mod: same mod at two indices → divisible subarray between them.; Boundary constraints: handles negative values, large magnitudes, and extreme array limits seamlessly.; Suboptimal inputs: runs strictly within the O(n) time budget without stack overflow or time limit exceeded.. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Subarray Sum Divisible by K?
Subarray Sum Divisible by K is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon, Google.
Buy me a coffee
Daily Practice
0/0