Check If Array Pairs Are Divisible by k - Problem

Given an array of integers arr of even length n and an integer k.

We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.

Return true if you can find a way to do that or false otherwise.

Input & Output

Example 1 — Basic Case
$ Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output: true
💡 Note: Pairs can be formed as: (1,9), (2,8), (3,7), (4,6), (5,10). Each pair sums to 10 which is divisible by 5.
Example 2 — Impossible Case
$ Input: arr = [1,2,3,4,5,6], k = 7
Output: true
💡 Note: Valid pairing: (1,6), (2,5), (3,4). Sums are 7, 7, 7 - all divisible by 7.
Example 3 — Remainder 0 Elements
$ Input: arr = [1,2,3,4,5,6], k = 10
Output: false
💡 Note: No valid pairing exists. Remainders are [1,2,3,4,5,6] and we need pairs that sum to divisible by 10.

Constraints

  • arr.length == n
  • 1 ≤ n ≤ 105
  • n is even
  • -109 ≤ arr[i] ≤ 109
  • 1 ≤ k ≤ 105

Visualization

Tap to expand
Check If Array Pairs Are Divisible by k INPUT arr = [1,2,3,4,5,10,6,7,8,9] 1 2 3 4 5 10 6 7 8 9 k = 5 Remainders when divided by 5: 1 2 3 4 0 0 1 2 3 4 n = 10, need 5 pairs ALGORITHM STEPS 1 Count Remainders freq[arr[i] % k]++ Remainder Frequency r=0 r=1 r=2 r=3 r=4 2 2 2 2 2 2 Check r=0 case freq[0] must be even freq[0]=2 (OK) 3 Match Complements freq[r] == freq[k-r] r=1 + r=4 2 == 2 (OK) r=2 + r=3 2 == 2 (OK) 4 All Checks Pass Return true FINAL RESULT Valid Pairs Found: (5, 10) 5+10=15 15%5=0 OK (1, 4) 1+4=5 5%5=0 OK (6, 9) 6+9=15 15%5=0 OK (2, 3) 2+3=5 5%5=0 OK (7, 8) 7+8=15 15%5=0 OK Output: true All 5 pairs are valid! Key Insight: For two numbers to have a sum divisible by k, their remainders (when divided by k) must add up to k (or 0). If remainder r pairs with (k-r), then freq[r] must equal freq[k-r]. Special case: freq[0] must be even (pairs with itself). Time Complexity: O(n) | Space Complexity: O(k) TutorialsPoint - Check If Array Pairs Are Divisible by k | Optimal Solution
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
78.0K Views
High Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen