Leetcode 2007: Find Original Array From Doubled Array

grid47
grid47
Exploring patterns and algorithms
Apr 20, 2024 7 min read

You are given an array changed, which may have been created by doubling each element of an original array and then shuffling the elements. Your task is to determine if changed can be converted back into the original array, where each element in the original array has its double present in changed. If changed is not a valid doubled array, return an empty array. If it is valid, return the original array.
Problem
Approach
Steps
Complexity
Input: The input consists of an array changed, which may be a shuffled version of the original array with each element doubled.
Example: changed = [2, 4, 1, 8, 3, 6]
Constraints:
• 1 <= changed.length <= 10^5
• 0 <= changed[i] <= 10^5
Output: Return the original array if it is valid, otherwise return an empty array.
Example: [1, 3, 4]
Constraints:
Goal: The goal is to check whether each element in changed has its double also in changed and return the original array or an empty array if it is not possible.
Steps:
• 1. Check if the size of changed is even, as there must be pairs of elements.
• 2. Sort the array to easily identify and pair the elements.
• 3. Use a frequency map to count occurrences of each element in changed.
• 4. For each element, check if its double exists in the map and decrease the counts accordingly.
• 5. Return the original array if all pairs are valid, otherwise return an empty array.
Goal: The input array is between 1 and 100,000 elements long, with values ranging from 0 to 100,000 for each element.
Steps:
• 1 <= changed.length <= 10^5
• 0 <= changed[i] <= 10^5
Assumptions:
• The solution should efficiently handle arrays of size up to 100,000.
• Handling large numbers and ensuring correctness of doubled pairs is critical.
Input: changed = [2, 4, 1, 8, 3, 6]
Explanation: The valid pairs are (1, 2), (3, 6), and (4, 8). Hence, the original array is [1, 3, 4].

Input: changed = [3, 0, 1, 6]
Explanation: Since there are no valid pairs, the output is an empty array.

Input: changed = [5]
Explanation: Since there is no pair for 5, the output is an empty array.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus