LeetCode Solutions

954. Array of Doubled Pairs

Time:

Space:

			

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;
  }
};
			

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;
  }
}
			

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