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
23
class Solution {
 public:
  bool canReorderDoubled(vector<int>& A) {
    unordered_map<int, int> count;

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

    sort(A.begin(), A.end(),
         [](const int a, const int b) { return abs(a) < abs(b); });

    for (int a : A) {
      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[] A) {
    Map<Integer, Integer> count = new HashMap<>();

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

    A = Arrays.stream(A)
            .boxed()
            .sorted((a, b) -> Math.abs(a) - Math.abs(b))
            .mapToInt(i -> i)
            .toArray();

    for (final int a : A) {
      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, A: List[int]) -> bool:
    count = Counter(A)

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

    return True