2007. Find Original Array From Doubled Array
UnknownView on LeetCode
Time: O(n log n)
Space: O(n)
Problem Overview
Find Original Array From Doubled Array (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Sort array; use a queue/map to match each element with its double; build original array.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Sort array; use a queue/map to match each element with its double; build original array.
Related patterns: Array, Hash Table
2007.cs
C#
// Approach: Sort array; use a queue/map to match each element with its double; build original array.
// Time: O(n log n) Space: O(n)
public class Solution
{
public int[] FindOriginalArray(int[] changed)
{
List<int> ans = new List<int>();
Queue<int> q = new Queue<int>();
Array.Sort(changed);
foreach (int num in changed)
{
if (q.Count > 0 && num == q.Peek())
q.Dequeue();
else
{
q.Enqueue(num * 2);
ans.Add(num);
}
}
return q.Count == 0 ? ans.ToArray() : new int[] { };
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)