#1497

Check If Array Pairs Are Divisible by k

Medium
ArrayHash TableCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(k)
💡

Intuition

Time O(n)Space O(k)

The optimal solution leverages the properties of modular arithmetic. By counting the frequencies of remainders when elements are divided by k, we can efficiently check if pairs can be formed that satisfy the divisibility condition.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a frequency array to count occurrences of each remainder when elements are divided by k.
  2. 2Step 2: For each remainder, check if it can be paired with its complement (k - remainder).
  3. 3Step 3: Special case for remainder 0: must have an even count.
  4. 4Step 4: Special case for k/2 if k is even: must also have an even count.
  5. 5Step 5: If all conditions are satisfied, return true; otherwise, return false.
solution.py11 lines
1# Full working Python code
2from collections import Counter
3
4def canArrange(arr, k):
5    remainder_count = Counter((num % k + k) % k for num in arr)
6    if remainder_count[0] % 2 != 0:
7        return False
8    for i in range(1, (k // 2) + 1):
9        if remainder_count[i] != remainder_count[k - i]:
10            return False
11    return True

Complexity note: The time complexity is linear because we traverse the array once to count remainders, and the space complexity is linear with respect to k for the frequency array.

  • 1Understanding modular arithmetic is crucial for solving problems involving divisibility.
  • 2Using frequency counts can significantly reduce the complexity of pairing problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.