LeetCode 2007: Find Original Array From Doubled Array Solution

Master LeetCode problem 2007 (Find Original Array From Doubled Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2007. Find Original Array From Doubled Array

Problem Explanation

Explanation:

To solve this problem, we can iterate over the changed array and build a frequency map of each element. Then, for each element x in the frequency map, we check if the frequency of 2*x is greater than or equal to the frequency of x. If this condition is satisfied, we decrement the frequency of 2*x by the frequency of x and continue to the next element. If at any point the condition is not met, we return an empty array.

Time Complexity:

The time complexity of this solution is O(n), where n is the number of elements in the changed array.

Space Complexity:

The space complexity of this solution is O(n), where n is the number of elements in the changed array.

Solution Code

import java.util.*;

class Solution {
    public int[] findOriginalArray(int[] changed) {
        if (changed.length % 2 != 0) {
            return new int[0];
        }
        
        Map<Integer, Integer> freqMap = new HashMap<>();
        
        for (int num : changed) {
            freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
        }
        
        List<Integer> result = new ArrayList<>();
        
        for (int num : changed) {
            if (freqMap.get(num) == 0) {
                continue;
            }
            
            if (freqMap.getOrDefault(2 * num, 0) < freqMap.get(num)) {
                return new int[0];
            }
            
            result.add(num);
            freqMap.put(num, freqMap.get(num) - 1);
            freqMap.put(2 * num, freqMap.get(2 * num) - 1);
        }
        
        return result.stream().mapToInt(Integer::intValue).toArray();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2007 (Find Original Array From Doubled Array)?

This page provides optimized solutions for LeetCode problem 2007 (Find Original Array From Doubled Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2007 (Find Original Array From Doubled Array)?

The time complexity for LeetCode 2007 (Find Original Array From Doubled Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2007 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2007 in Java, C++, or Python.

Back to LeetCode Solutions