Make Sum Divisible by P
Problem Statement
You are given an array nums of positive integers and a number p.
You may delete one contiguous subarray (possibly empty) so that the sum of what is left is divisible by p. You are not allowed to delete the whole array.
Return the length of the shortest subarray you need to delete, or -1 if it cannot be done.
An integer array nums (all values ≥ 1) and an integer p (p ≥ 1).
The smallest length of a subarray to remove (0 if the sum is already divisible), or −1 if only removing everything would work.
The total is 10. Remove [4] and the rest sums to 6.
The total is 16. No single element works, but removing [5, 2] leaves [6, 3] with sum 9.
The total 6 is already divisible by 3, so remove nothing.
The total is 6. Only removing the whole array would leave a sum divisible by 7, and that is not allowed.
- • 1 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^9
- • 1 ≤ p ≤ 10^9
- • The total can reach 10^14 — use a 64-bit type or keep everything mod p.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try every subarray; keep the shortest whose sum % p == need
Look up remainder (cur − need) mod p; store the latest index of each remainder
Compute need = total % p. For every start, grow the end and keep the piece's remainder. Whenever it equals need, the rest is divisible by p, so record the length. Ignore the whole array.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Prefix Sum translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.