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 karr = [1,2,3,4,5,6], k = 7123456Pair 1: 1 + 6 = 7 ✓Pair 2: 2 + 5 = 7 ✓Pair 3: 3 + 4 = 7 ✓All pairs sum to multiples of k=7Result: trueKey insight: Use remainder frequencies to check pairing validity in O(n) time
Understanding the Visualization
1
Input Array
Array of integers and target divisor k
2
Find Valid Pairs
Group elements where each pair sum is divisible by k
3
Verify Result
Check if all elements can be paired
Key Takeaway
🎯 Key Insight: Two numbers can pair if their remainders when divided by k sum to k (or both are 0)
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