Check If Array Pairs Are Divisible by k LeetCode solution in Python

1
# Runtime: 556 ms (Top 81.4%) | Memory: 30.00 MB (Top 97.8%)
2

3

4
class Solution:
5
def canArrange(self, arr: List[int], k: int) -> bool:
6
# The idea is to count the residues
7

8
# If every residue has the counter residue
9
# such that x+y == k,then we found a pair
10

11
count = [0] * k
12
for num in arr:
13
count[num % k] += 1
14

15
# Now since we have 0,1,2,.....k-1 as residues
16
# If count[1] == count[k-1],pairs+=count[1]
17
# since we have odd number of complimenting residues,
18
# we should also care about residue=0 and residue=k//2
19

20
i, j = 1, k - 1
21
pairs = 0
22
while i < j:
23
if count[i] != count[j]:
24
return False
25
pairs += count[i]
26
i += 1
27
j -= 1
28
if pairs > 0 and i == j:
29
pairs += count[i] / 2
30
pairs += count[0] / 2
31
n = len(arr)
32
return pairs == n // 2

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0