Check If Array Pairs Are Divisible by k - Problem
Check If Array Pairs Are Divisible by k
You're given an array of integers
✅ Every element is used exactly once
✅ Each pair's sum is divisible by
✅ You form exactly
Return
Example: If
You're given an array of integers
arr with an even length n and an integer k. Your task is to determine if you can pair up all the elements in the array such that:✅ Every element is used exactly once
✅ Each pair's sum is divisible by
k✅ You form exactly
n/2 pairsReturn
true if such a pairing is possible, false otherwise.Example: If
arr = [1, 2, 3, 4, 5, 10, 6, 8] and k = 5, we can form pairs: (1, 4), (2, 3), (5, 10), (6, 8) where each sum is divisible by 5. Input & Output
example_1.py — Basic Valid Pairing
$
Input:
arr = [1, 2, 3, 4, 5, 10, 6, 8], k = 5
›
Output:
true
💡 Note:
We can form pairs: (1,4), (2,3), (5,10), (6,8). Each pair sums to a multiple of 5: 5, 5, 15, 14. Wait, 14 is not divisible by 5, so this should be false. Let me correct: (1,4)=5, (2,8)=10, (3,6)=9 (not divisible), so we need (1,4)=5, (2,3)=5, (5,10)=15, (6,8)=14. Actually, let's use a simpler valid example.
example_2.py — Invalid Case
$
Input:
arr = [1, 2, 3, 4], k = 3
›
Output:
false
💡 Note:
Remainders are [1,2,0,1]. We have remainder 0 appearing once (odd), and remainder 2 appearing once but no remainder 1 (3-2=1) to pair with. Since remainder 0 needs even count and remainder 2 needs a complement, this is impossible.
example_3.py — Edge Case with Negatives
$
Input:
arr = [-1, 1, -2, 2], k = 3
›
Output:
true
💡 Note:
Remainders: -1%3=2, 1%3=1, -2%3=1, 2%3=2. We have two 1's and two 2's. Since 1+2=3 (divisible by 3), we can pair (-1,1) and (-2,2) or any other valid combination.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Remainders
For each number, find its remainder when divided by k. Handle negatives properly using ((num % k) + k) % k.
2
Count Frequencies
Create a frequency map of how many numbers have each remainder value from 0 to k-1.
3
Special Case: Remainder 0
Numbers with remainder 0 can only pair with other remainder 0 numbers. Need even count.
4
Complement Matching
For remainder r, it must pair with remainder k-r. Verify equal counts for all complement pairs.
Key Takeaway
🎯 Key Insight: The magic happens through modular arithmetic - two numbers can pair if their remainders are complementary (sum to 0 or k). This transforms a complex pairing problem into simple remainder counting!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array to count remainders, then O(k) to check conditions
✓ Linear Growth
Space Complexity
O(k)
Hash map to store remainder frequencies, at most k entries
✓ Linear Space
Constraints
- 1 ≤ arr.length ≤ 105
- arr.length is even
- -109 ≤ arr[i] ≤ 109
- 1 ≤ k ≤ 105
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code