Find original sequence from Array containing the sequence merged many times in order - GeeksforGeeks

26 Oct, 2021
Given a number N and an array arr[] that consist of merging N length sequence of distinct integers any number of times maintaining the relative order of elements in the initial sequence. The task is to find the initial sequence of length N maintaining the right order. 
Examples:
Input: N = 4, arr[] = {1, 13, 1, 24, 13, 24, 2, 2}Output: 1 13 24 2 Explanation: Here the given sequence is obtained by merging 1 13 24 2 maintaining the relative order of elements. Therefore, the answer is 1 13 24 2.
Input: N = 3, arr[] = {3, 2, 3, 1, 2, 3, 2, 1, 1}Output: 3 2 1Explanation:Here the given sequence is obtained by merging 3 2 1 maintaining the relative order of elements. Therefore, the answer is 3 2 1.
Approach: The idea is to observe that the element occurring first in the given sequence is the first element of the resultant restored sequence. Take that element in our restored sequence and don’t include duplicate from the given sequence. Perform the same for the rest of the elements until we reach the end. The idea can be implemented by both Map and Set in C++.
Using Map
Traverse through the given sequence from left to right.The element coming for the first time in the sequence is taken into account and marked using a map.Elements that are marked while traversing are ignored.Step 2 and Step 3 is continued until the end of the given sequence is reached.
Traverse through the given sequence from left to right.
The element coming for the first time in the sequence is taken into account and marked using a map.
Elements that are marked while traversing are ignored.
Step 2 and Step 3 is continued until the end of the given sequence is reached.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the restored// permutationvector<int> restore(int arr[], int N){    // Vector to store the result    vector<int> result;     // Map to mark the elements    // which are taken in result    map<int, int> mp;    for (int i = 0; i < N; i++) {         // Check if the element is        // coming first time        if (mp[arr[i]] == 0) {             // Push in result vector            result.push_back(arr[i]);             // Mark it in the map            mp[arr[i]]++;        }    }     // Return the answer    return result;} // Function to print the resultvoid print_result(vector<int> result){    for (int i = 0; i < result.size(); i++)        cout << result[i] << " ";} // Driver Codeint main(){    // Given Array    int arr[] = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function Call    print_result(restore(arr, N));    return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function that returns the restored// permutationstatic Vector<Integer> restore(int arr[], int N){    // Vector to store the result    Vector<Integer> result = new Vector<>();     // Map to mark the elements    // which are taken in result    HashMap<Integer,            Integer> mp = new HashMap<Integer,                                      Integer>();    for (int i = 0; i < N; i++)    {         // Check if the element is        // coming first time        if (mp.containsKey(arr[i]) &&            mp.get(arr[i]) == 0)        {             // Push in result vector            result.add(arr[i]);             // Mark it in the map            if(mp.containsKey(arr[i]))            {                mp.put(arr[i], mp.get(arr[i]) + 1);            }            else            {                mp.put(arr[i], 1);            }        }        else            mp.put(arr[i], 0);    }     // Return the answer    return result;} // Function to print the resultstatic void print_result(Vector<Integer> result){    for (int i = 0; i < result.size(); i++)        System.out.print(result.get(i) + " ");} // Driver Codepublic static void main(String[] args){    // Given Array    int arr[] = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = arr.length;     // Function Call    print_result(restore(arr, N));}} // This code is contributed by Rajput-Ji
# Python3 program for the above approach # Function that returns the restored# permutationdef restore(arr, N):         # List to store the result    result = []         # Map to mark the elements    # which are taken in result    mp = {}         for i in range(N):                 # Checking if the element is        # coming first time        if not arr[i] in mp:                         # Push in result vector            result.append(arr[i])                         # Mark it in the map            mp[arr[i]] = 1                 # Return the answer    return result # Function to print the resultdef print_result(result):         for i in range(len(result)):        print(result[i], end = " ")         # Driver codedef main():         # Given array    arr = [ 1, 13, 1, 24, 13, 24, 2, 2 ]    N = len(arr)         # Function call    print_result(restore(arr, N))     main()     # This code is contributed by Stuti Pathak
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function that returns the restored// permutationstatic List<int> restore(int []arr, int N){         // List to store the result    List<int> result = new List<int>();     // Map to mark the elements    // which are taken in result    Dictionary<int,               int> mp = new Dictionary<int,                                        int>();    for(int i = 0; i < N; i++)    {                 // Check if the element is        // coming first time        if (mp.ContainsKey(arr[i]) &&            mp[arr[i]] == 0)        {                         // Push in result vector            result.Add(arr[i]);             // Mark it in the map            if(mp.ContainsKey(arr[i]))            {                mp[arr[i]] = mp[arr[i]] + 1;            }            else            {                mp.Add(arr[i], 1);            }        }        else            mp.Add(arr[i], 0);    }     // Return the answer    return result;} // Function to print the resultstatic void print_result(List<int> result){    for(int i = 0; i < result.Count; i++)        Console.Write(result[i] + " ");} // Driver Codepublic static void Main(String[] args){         // Given Array    int []arr = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = arr.Length;     // Function call    print_result(restore(arr, N));}} // This code is contributed by 29AjayKumar
<script>  // Javascript program for the above approach // Function that returns the restored// permutationfunction restore(arr, N){    // Vector to store the result    var result = [];     // Map to mark the elements    // which are taken in result    var mp = new Map();     for (var i = 0; i < N; i++) {         // Check if the element is        // coming first time        if (!mp.has(arr[i])) {             // Push in result vector            result.push(arr[i]);             // Mark it in the map            mp.set(arr[i], mp.get(arr[i])+1);        }    }     // Return the answer    return result;} // Function to print the resultfunction print_result(result){    for (var i = 0; i < result.length; i++)    {        document.write( result[i] + " ");    }         } // Driver Code// Given Arrayvar arr = [1, 13, 1, 24, 13, 24, 2, 2];var N = arr.length;// Function Callprint_result(restore(arr, N)); </script>
1 13 24 2
 
Time Complexity: O(N)Auxiliary Space: O(N)
Using Set
Traverse through the given sequence from left to right.A counter is taken and initialized as 1.Insert the elements into the set one by one. If at some point that the size of the set and the counter is the same, the element is taken into account and the counter is increased by 1.Step 3 and Step 4 is continued until the end of the given sequence is reached.
Traverse through the given sequence from left to right.
A counter is taken and initialized as 1.
Insert the elements into the set one by one. If at some point that the size of the set and the counter is the same, the element is taken into account and the counter is increased by 1.
Step 3 and Step 4 is continued until the end of the given sequence is reached.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that returns the restored// permutationvector<int> restore(int arr[], int N){    // Vector to store the result    vector<int> result;    int count1 = 1;     // Set to insert unique elements    set<int> s;    for (int i = 0; i < N; i++) {         s.insert(arr[i]);         // Check if the element is        // coming first time        if (s.size() == count1) {             // Push in result vector            result.push_back(arr[i]);             count1++;        }    }     return result;} // Function to print the resultvoid print_result(vector<int> result){    for (int i = 0; i < result.size(); i++)        cout << result[i] << " ";} // Driver Codeint main(){    // Given Array    int arr[] = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function Call    print_result(restore(arr, N));    return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function that returns the restored// permutationstatic Vector<Integer> restore(int arr[], int N){         // Vector to store the result    Vector<Integer> result = new Vector<Integer>();         int count1 = 1;     // Set to insert unique elements    HashSet<Integer> s = new HashSet<Integer>();         for(int i = 0; i < N; i++)    {        s.add(arr[i]);         // Check if the element is        // coming first time        if (s.size() == count1)        {                         // Push in result vector            result.add(arr[i]);            count1++;        }    }    return result;} // Function to print the resultstatic void print_result(Vector<Integer> result){    for(int i = 0; i < result.size(); i++)        System.out.print(result.get(i) + " ");} // Driver Codepublic static void main(String[] args){         // Given Array    int arr[] = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = arr.length;     // Function call    print_result(restore(arr, N));}} // This code is contributed by Princi Singh
# Python3 program for the# above approach # Function that returns the# restored permutationdef restore(arr, N):     # Vector to store the    # result    result = []    count1 = 1     # Set to insert unique    # elements    s = set([])         for i in range(N):        s.add(arr[i])         # Check if the element is        # coming first time        if (len(s) == count1):             # Push in result vector            result.append(arr[i])             count1 += 1     return result # Function to print the# resultdef print_result(result):     for i in range(len(result)):        print(result[i],              end = " ") # Driver Codeif __name__ == "__main__":     # Given Array    arr = [1, 13, 1, 24,           13, 24, 2, 2]     N = len(arr)     # Function Call    print_result(restore(arr, N)) # This code is contributed by Chitranayal
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function that returns the restored// permutationstatic List<int> restore(int []arr, int N){         // List to store the result    List<int> result = new List<int>();         int count1 = 1;     // Set to insert unique elements    HashSet<int> s = new HashSet<int>();         for(int i = 0; i < N; i++)    {        s.Add(arr[i]);         // Check if the element is        // coming first time        if (s.Count == count1)        {                         // Push in result vector            result.Add(arr[i]);            count1++;        }    }    return result;} // Function to print the resultstatic void print_result(List<int> result){    for(int i = 0; i < result.Count; i++)        Console.Write(result[i] + " ");} // Driver Codepublic static void Main(String[] args){         // Given Array    int []arr = { 1, 13, 1, 24, 13, 24, 2, 2 };     int N = arr.Length;     // Function call    print_result(restore(arr, N));}} // This code is contributed by PrinciRaj1992
<script> // Javascript program for the above approach // Function that returns the restored// permutationfunction restore(arr, N){         // Vector to store the result    let result = [];          let count1 = 1;      // Set to insert unique elements    let s = new Set();          for(let i = 0; i < N; i++)    {        s.add(arr[i]);          // Check if the element is        // coming first time        if (s.size == count1)        {                         // Push in result vector            result.push(arr[i]);            count1++;        }    }    return result;} // Function to print the resultfunction print_result(result){    for(let i = 0; i < result.length; i++)        document.write(result[i] + " ");} // Driver Codelet arr = [ 1, 13, 1, 24, 13, 24, 2, 2 ];let N = arr.length; // Function callprint_result(restore(arr, N)); // This code is contributed by avanitrachhadiya2155 </script>
1 13 24 2
 
Time Complexity: O(N)Auxiliary Space: O(N)
stutipathak31jan
princi singh
princiraj1992
Rajput-Ji
29AjayKumar
ukasp
famously
avanitrachhadiya2155
simranarora5sos
cpp-map
cpp-set
permutation
Arrays
Pattern Searching
Arrays
permutation
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching