Skip to content

954. Array of Doubled Pairs 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  bool canReorderDoubled(vector<int>& arr) {
    unordered_map<int, int> count;

    for (const int a : arr)
      ++count[a];

    ranges::sort(arr, ranges::less{}, [](const int a) { return abs(a); });

    for (const int a : arr) {
      if (count[a] == 0)
        continue;
      if (count[2 * a] == 0)
        return false;
      --count[a];
      --count[2 * a];
    }

    return true;
  }
};
 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
class Solution {
  public boolean canReorderDoubled(int[] arr) {
    Map<Integer, Integer> count = new HashMap<>();

    for (final int a : arr)
      count.merge(a, 1, Integer::sum);

    arr = Arrays.stream(arr)
              .boxed()
              .sorted((a, b) -> Integer.compare(Math.abs(a), Math.abs(b)))
              .mapToInt(Integer::intValue)
              .toArray();

    for (final int a : arr) {
      if (count.get(a) == 0)
        continue;
      if (count.getOrDefault(2 * a, 0) == 0)
        return false;
      count.merge(a, -1, Integer::sum);
      count.merge(2 * a, -1, Integer::sum);
    }

    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def canReorderDoubled(self, arr: list[int]) -> bool:
    count = collections.Counter(arr)

    for key in sorted(count, key=abs):
      if count[key] > count[2 * key]:
        return False
      count[2 * key] -= count[key]

    return True