-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.cpp
35 lines (32 loc) · 986 Bytes
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution
{
public:
bool canArrange(vector<int> &arr, int k)
{
// Frequency array to store the count of remainders
vector<int> remainderFreq(k, 0);
// Step 1: Calculate the remainder for each element and store the frequency
for (int num : arr)
{
int remainder = ((num % k) + k) % k; // Ensure non-negative remainder
remainderFreq[remainder]++;
}
// Step 2: Check if the pairing condition holds
for (int i = 0; i <= k / 2; i++)
{
if (i == 0)
{
// Elements with remainder 0 must pair among themselves
if (remainderFreq[i] % 2 != 0)
return false;
}
else
{
// Remainder i must pair with remainder k-i
if (remainderFreq[i] != remainderFreq[k - i])
return false;
}
}
return true;
}
};