Find elements of original array from doubled array

- Given an array arr[] of 2*N integers such that it consists of all elements along with the twice values of another array, say A[], the task is to find the array A[].
Examples:
Input: arr[] = {4, 1, 18, 2, 9, 8}
Output: 1 4 9
Explanation:
After taking double values of 1, 4, and 9 then adding them to the original array, All elements of the given array arr[] are obtainedÂInput: arr[] = {4, 1, 2, 2, 8, 2, 4, 4}
Output: 1 2 2 4
Approach: The given problem can be solved by counting the frequency of array elements in the HashMap array elements and observation can be made that, the smallest element in the array will always be a part of the original array, therefore it can be included in the result list res[]. The element with a double value of the smallest element will be the duplicate element that is not part of the original array so its frequency can be reduced from the map. Below steps can be followed to solve the problem:Â
- Sort the given array arr[] in ascending order
- Iterate through the array elements and store the numbers and their frequencies in a hashmap
- Create a result list res[] to store the elements present in the original list
- Add the first element in the result list and reduce the frequency of the element which has a double value of the first element.
- Traverse the array and check for the frequency of every element in the map:
- If the frequency is greater than 0, then add the element in the result list and decrement the frequency.
- Otherwise, skip the element and move ahead because it is a double value and not a part of the original array.
- After completing the above steps, print the elements in the list res[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the original array// from the doubled arrayvector<int> findOriginal(vector<int>& arr){Â
    // Stores the numbers and    // their frequency    map<int, int> numFreq;Â
    // Add number with their frequencies    // in the hashmap    for (int i = 0; i < arr.size(); i++) {        numFreq[arr[i]]++;    }Â
    // Sort the array    sort(arr.begin(), arr.end());Â
    // Initialize an arraylist    vector<int> res;Â
    for (int i = 0; i < arr.size(); i++) {Â
        // Get the frequency of the number        int freq = numFreq[arr[i]];        if (freq > 0) {Â
            // Element is of original array            res.push_back(arr[i]);Â
            // Decrement the frequency of            // the number            numFreq[arr[i]]--;Â
            int twice = 2 * arr[i];Â
            // Decrement the frequency of            // the number having double value            numFreq[twice]--;        }    }Â
    // Return the resultant string    return res;}Â
// Driver Codeint main(){Â
    vector<int> arr = { 4, 1, 2, 2, 2, 4, 8, 4 };    vector<int> res = findOriginal(arr);Â
    // Print the result list    for (int i = 0; i < res.size(); i++) {        cout << res[i] << " ";    }Â
    return 0;}Â
    // This code is contributed by rakeshsahni |
Java
// Java program for the above approachÂ
import java.io.*;import java.util.*;class GFG {Â
    // Function to find the original array    // from the doubled array    public static List<Integer>    findOriginal(int[] arr)    {Â
        // Stores the numbers and        // their frequency        Map<Integer, Integer> numFreq            = new HashMap<>();Â
        // Add number with their frequencies        // in the hashmap        for (int i = 0; i < arr.length; i++) {            numFreq.put(                arr[i],                numFreq.getOrDefault(arr[i], 0)                    + 1);        }Â
        // Sort the array        Arrays.sort(arr);Â
        // Initialize an arraylist        List<Integer> res = new ArrayList<>();Â
        for (int i = 0; i < arr.length; i++) {Â
            // Get the frequency of the number            int freq = numFreq.get(arr[i]);            if (freq > 0) {Â
                // Element is of original array                res.add(arr[i]);Â
                // Decrement the frequency of                // the number                numFreq.put(arr[i], freq - 1);Â
                int twice = 2 * arr[i];Â
                // Decrement the frequency of                // the number having double value                numFreq.put(                    twice,                    numFreq.get(twice) - 1);            }        }Â
        // Return the resultant string        return res;    }Â
    // Driver Code    public static void main(String[] args)    {Â
        List<Integer> res = findOriginal(            new int[] { 4, 1, 2, 2, 2, 4, 8, 4 });Â
        // Print the result list        for (int i = 0; i < res.size(); i++) {            System.out.print(                res.get(i) + " ");        }    }} |
Python3
# Python program for the above approachÂ
# Function to find the original array# from the doubled arraydef findOriginal(arr):Â
    # Stores the numbers and    # their frequency    numFreq = {}Â
    # Add number with their frequencies    # in the hashmap    for i in range(0, len(arr)):        if (arr[i] in numFreq):            numFreq[arr[i]] += 1        else:            numFreq[arr[i]] = 1Â
    # Sort the array    arr.sort()Â
    # Initialize an arraylist    res = []Â
    for i in range(0, len(arr)):               # Get the frequency of the number        freq = numFreq[arr[i]]        if (freq > 0):                       # Element is of original array            res.append(arr[i])Â
            # Decrement the frequency of            # the number            numFreq[arr[i]] -= 1Â
            twice = 2 * arr[i]Â
            # Decrement the frequency of            # the number having double value            numFreq[twice] -= 1Â
    # Return the resultant string    return resÂ
# Driver Codearr = [4, 1, 2, 2, 2, 4, 8, 4]res = findOriginal(arr)Â
# Print the result listfor i in range(0, len(res)):Â Â Â Â print(res[i], end=" ")Â
Â
# This code is contributed by _Saurabh_Jaiswal |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG {Â
    // Function to find the original array    // from the doubled array    public static List<int> findOriginal(int[] arr)    {Â
        // Stores the numbers and        // their frequency        Dictionary<int, int> numFreq = new Dictionary<int, int>();Â
        // Add number with their frequencies        // in the hashmap        for (int i = 0; i < arr.Length; i++) {             if(numFreq.ContainsKey(arr[i])){                numFreq[arr[i]] = numFreq[arr[i]] + 1;            }else{                numFreq.Add(arr[i], 1);            }        }Â
        // Sort the array        Array.Sort(arr);Â
        // Initialize an arraylist        List<int> res = new List<int>();Â
        for (int i = 0; i < arr.Length; i++) {Â
            // Get the frequency of the number            int freq = numFreq[arr[i]];            if (freq > 0) {Â
                // Element is of original array                res.Add(arr[i]);Â
                // Decrement the frequency of                // the number                numFreq[arr[i]] = freq - 1;Â
                int twice = 2 * arr[i];Â
                // Decrement the frequency of                // the number having double value                numFreq[twice] = numFreq[twice] - 1;            }        }Â
        // Return the resultant string        return res;    }Â
    // Driver Code    public static void Main()    {Â
        List<int> res = findOriginal(new int[] { 4, 1, 2, 2, 2, 4, 8, 4 });Â
        // Print the result list        for (int i = 0; i < res.Count; i++) {            Console.Write(res[i] + " ");        }    }}Â
// This code is contributed by gfgking. |
Javascript
<script>// Javascript program for the above approachÂ
// Function to find the original array// from the doubled arrayfunction findOriginal(arr) {Â
  // Stores the numbers and  // their frequency  let numFreq = new Map();Â
  // Add number with their frequencies  // in the hashmap  for (let i = 0; i < arr.length; i++) {    if (numFreq.has(arr[i])) {      numFreq.set(arr[i], numFreq.get(arr[i]) + 1);    } else {      numFreq.set(arr[i], 1);    }  }Â
  // Sort the array  arr.sort((a, b) => a - b);Â
  // Initialize an arraylist  let res = [];Â
  for (let i = 0; i < arr.length; i++) {    // Get the frequency of the number    let freq = numFreq.get(arr[i]);    if (freq > 0) {      // Element is of original array      res.push(arr[i]);Â
      // Decrement the frequency of      // the number      numFreq.set(arr[i], numFreq.get(arr[i]) - 1);Â
      let twice = 2 * arr[i];Â
      // Decrement the frequency of      // the number having double value      numFreq.set(twice, numFreq.get(twice) - 1);    }  }Â
  // Return the resultant string  return res;}Â
// Driver CodeÂ
let arr = [4, 1, 2, 2, 2, 4, 8, 4];let res = findOriginal(arr);Â
// Print the result listfor (let i = 0; i < res.length; i++) {Â Â document.write(res[i] + " ");}Â
// This code is contributed by gfgking.</script> |
1 2 2 4
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



