Check If Array Pairs Are Divisible by k — LeetCode 1497 Python Solution

MediumArrayHash TableCounting
Problem
#1497
Pattern
Hash Map
Reading time
2 min

The 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.

Example

Input
arr = [1,2,3,4,5,10,6,7,8,9], k = 5
Output
true
Explanation
Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).

Python solution

Python
class Solution:
    def canArrange(self, arr: List[int], k: int) -> bool:
        cnt = Counter(x % k for x in arr)
        return cnt[0] % 2 == 0 and all(cnt[i] == cnt[k - i] for i in range(1, k))

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{arr}
SpaceO(k) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1497. Check If Array Pairs Are Divisible by k is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1497. Check If Array Pairs Are Divisible by k?
LeetCode 1497. Check If Array Pairs Are Divisible by k is rated Medium on LeetCode.
What is the time complexity of LeetCode 1497. Check If Array Pairs Are Divisible by k?
The Python solution on this page runs in O(n), where n is the length of the array \textit{arr}.
What is the space complexity of LeetCode 1497. Check If Array Pairs Are Divisible by k?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 1497. Check If Array Pairs Are Divisible by k cover?
LeetCode 1497. Check If Array Pairs Are Divisible by k is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview