We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 181be92 commit 8d9c1feCopy full SHA for 8d9c1fe
array_of_doubled_pairs.cpp
@@ -0,0 +1,29 @@
1
+class Solution {
2
+public:
3
+ bool canReorderDoubled(vector<int>& arr) {
4
+ if(arr.size() == 0) return true;
5
+
6
+ unordered_map<int, int> ump; //element to count
7
+ sort(arr.begin(), arr.end());
8
9
+ for(auto element : arr) {
10
+ ump[element]++;
11
+ }
12
13
+ for(auto element: arr) {
14
+ if (ump[element] == 0) {
15
+ continue;
16
17
+ if (element < 0 && element % 2 != 0) { //for -ve values, there is no element/2 pair to match
18
+ return false;
19
20
+ int pair = element > 0 ? element*2 : element/2; //positive or negative
21
+ if (ump[pair] == 0) { //no match with element
22
23
24
+ ump[element]--;
25
+ ump[pair]--;
26
27
+ return true;
28
29
+};
0 commit comments