Skip to content

2007. Find Original Array From Doubled Array 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> findOriginalArray(vector<int>& changed) {
    vector<int> ans;
    queue<int> q;

    ranges::sort(changed);

    for (const int num : changed)
      if (!q.empty() && num == q.front()) {
        q.pop();
      } else {
        q.push(num * 2);
        ans.push_back(num);
      }

    return q.empty() ? ans : vector<int>();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] findOriginalArray(int[] changed) {
    List<Integer> ans = new ArrayList<>();
    Queue<Integer> q = new ArrayDeque<>();

    Arrays.sort(changed);

    for (final int num : changed)
      if (!q.isEmpty() && num == q.peek()) {
        q.poll();
      } else {
        q.offer(num * 2);
        ans.add(num);
      }

    return q.isEmpty() ? ans.stream().mapToInt(Integer::intValue).toArray() : new int[] {};
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def findOriginalArray(self, changed: list[int]) -> list[int]:
    ans = []
    q = collections.deque()

    for num in sorted(changed):
      if q and num == q[0]:
        q.popleft()
      else:
        q.append(num * 2)
        ans.append(num)

    return [] if q else ans