Check If Array Pairs Are Divisible by k — LeetCode 1497 Python Solution
- Problem
- #1497
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{arr} |
| Space | O(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.