Check If Array Pairs Are Divisible by k

You are given an integer array `arr` of even length `n` and an integer `k`. Split the array into exactly `n / 2` pairs so that the sum of each pair is divisible by `k`. Return `true` if such a split exists, or `false` otherwise.

30:00

Check If Array Pairs Are Divisible by k
medium
Free written solution
Topics
Companies

You are given an integer array arr of even length n and an integer k.

Split the array into exactly n / 2 pairs so that the sum of each pair is divisible by k.

Return true if such a split exists, or false otherwise.

Example 1:
Input: {"arr":[1,2,3,4,5,10,6,7,8,9],"k":5}
Output: true
Constraints:
  • arr.length == n

  • 1≤n≤1051 \leq n \leq 10^5

  • n is even.

  • −109≤arr[i]≤109-10^9 \leq \text{arr}[i] \leq 10^9

  • 1≤k≤1051 \leq k \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"arr":[1,2,3,4,5,10,6,7,8,9],"k":5}

A pair sums to a multiple of 5 exactly when its remainders add up to 5 (or are both 0). So only the remainder of each number matters: sort them into 5 buckets.

arr, remainder below

1

·

2

·

3

·

4

·

5

·

10

·

6

·

7

·

8

·

9

·

remainder clock, k = 5

0001020304k = 5buckets

remainder buckets around the clock; number inside = count, outside = remainder

Variables
VariableValue
k5
DepthFunction Call
Stack empty
0/14