Open In App

Print Array after moving first occurrence of given element to end in given Array for Q queries

Last Updated : 08 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers and an array query[] having Q integers, the task is to print the array arr[] after moving the first occurrence of query[i] to the end of the array arr[] for each i in the range [0, Q).

Example:

Input: arr[] = {1, 3, 1, 3}, query[] = {3, 1}
Output: 1 3 3 1
Explanation: In 1st iteration, send first occurrence of query[0] to the end, i.e, send first occurrence of 3 to the end. 
Hence, the array becomes arr[] = {1, 1, 3, 3}. 
In 2nd iteration, send first occurrence of query[1] to the end. 
Hence, array arr[] = {1, 3, 3, 1} which is the required array.

Input: arr[] = {1, 2, 3, 4, 5}, query[] = {4, 3}
Output: 1 2 5 4 3

 

Approach: The given problem can be solved using hashing. The idea is to store the list of indices of each integer in a set data structure, and for an operation on the current integer, remove the 1st index from the set representing the index of the first occurrence of the current integer and insert the index of the last index into the set. Below are the steps to follow:

  • Create an unordered map m, storing the set of indices for each index.
  • Iterate the array arr[] and insert all the indices into their respective sets in the map m.
  • Iterate the array query[] using a variable i and perform the following operations:
    • Remove the first element representing the first occurrence from the set m[query[i]].
    • Insert the index of the last element i.e, N+i into the set m[query[i]].
  • Print the elements in increasing order of their final indices which is the required answer.

Below is the implementation of the above approach:

C++14




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the array after
// performing the given operations
void sendToLast(vector<int> arr,
                vector<int> query)
{
    // Stores index of present
    // integers in a set
    unordered_map<int, set<int> > m;
 
    // Loop to insert indices
    // into the given map
    for (int i = 0; i < arr.size(); i++) {
        m[arr[i]].insert(i);
    }
 
    // Loop to iterate the
    // query array
    for (int i = 0; i < query.size(); i++) {
 
        // Erase the index of current
        // element from the map
        m[query[i]].erase(*m[query[i]].begin());
 
        // Insert new location
        m[query[i]].insert(arr.size() + i);
    }
 
    // Vector of pair to store index
    // value pair
    vector<pair<int, int> > v;
 
    // Insert all index value pair
    // into the vector v
    for (auto x : m) {
        for (auto y : x.second) {
            v.push_back({ y, x.first });
        }
    }
 
    // Sort v in increasing order
    // of the index
    sort(v.begin(), v.end());
 
    // Print array
    for (int i = 0; i < v.size(); i++) {
        cout << v[i].second << " ";
    }
}
 
// Driver Code
int main()
{
    vector<int> arr{ 1, 3, 1, 3 };
    vector<int> query{ 3, 1 };
 
    sendToLast(arr, query);
    return 0;
}


Java




// Java program of the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to print the array after
  // performing the given operations
  static void sendToLast(int[] arr, int[] query)
  {
    // Stores index of present
    // integers in a set
    Map<Integer, Set<Integer> > m = new HashMap<>();
 
    // Loop to insert indices
    // into the given map
    for (int i = 0; i < arr.length; i++) {
      m.computeIfAbsent(arr[i], k -> new HashSet<>())
        .add(i);
    }
 
    // Loop to iterate the
    // query array
    for (int i = 0; i < query.length; i++) {
      // Erase the index of current
      // element from the map
      m.get(query[i]).remove(
        m.get(query[i]).iterator().next());
 
      // Insert new location
      m.get(query[i]).add(arr.length + i);
    }
 
    // Vector of pair to store index
    // value pair
    List<Map.Entry<Integer, Integer> > v
      = new ArrayList<>();
 
    // Insert all index value pair
    // into the vector v
    for (Map.Entry<Integer, Set<Integer> > x :
         m.entrySet()) {
      for (int y : x.getValue()) {
        v.add(new AbstractMap.SimpleEntry<>(
          y, x.getKey()));
      }
    }
 
    // Sort v in increasing order
    // of the index
    v.sort(Map.Entry.comparingByKey());
 
    // Print array
    for (Map.Entry<Integer, Integer> entry : v) {
      System.out.print(entry.getValue() + " ");
    }
  }
 
  public static void main(String[] args)
  {
    int[] arr = { 1, 3, 1, 3 };
    int[] query = { 3, 1 };
 
    sendToLast(arr, query);
  }
}
 
// This code is contributed by lokesh.


Python3




# Python program for the above approach
 
# Function to print array after
# performing the given operations
def sendToLast(arr, query):
   
    # Stores index of present
    # integers in a set
    m = {}
     
    # Loop to insert indices
    # into the given map
    for i in range(len(arr)):
        if arr[i] not in m:
            m[arr[i]] = []
        m[arr[i]].append(i)
         
    # Loop to iterate the
    # query array
    for i in range(len(query)):
       
        # Erase the index of current
        # element from the map    
        m[query[i]] = m[query[i]][1:] #-.erase(*m[query[i]].begin())
         
        # Insert new location
        m[query[i]].append(len(arr) + i)
         
    # Vector of pair to store index
    # value pair
    v =[]
     
    # Insert all index value pair
    # into the vector v
    for x in m:
        for y in m[x]:
            v.append([y, x])
             
    # Sort v in increasing order
    # of the index
    v.sort()
     
    # Print array
    for i in range(len(v)):
        print(v[i][1], end = " ")
 
# Driver Code
arr =  [1, 3, 1, 3]
query = [3, 1]
 
sendToLast(arr, query)
 
# This code is contributed by Shubham Singh


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
 
    // Function to print the array after
    // performing the given operations
    static void SendToLast(int[] arr, int[] query)
    {
        // Stores index of present
        // integers in a dictionary
        Dictionary<int, HashSet<int> > m
            = new Dictionary<int, HashSet<int> >();
 
        // Loop to insert indices
        // into the given dictionary
        for (int i = 0; i < arr.Length; i++) {
            if (!m.ContainsKey(arr[i])) {
                m[arr[i]] = new HashSet<int>();
            }
            m[arr[i]].Add(i);
        }
 
        // Loop to iterate the
        // query array
        for (int i = 0; i < query.Length; i++) {
            // Erase the index of current
            // element from the dictionary
            int idx = m[query[i]].First();
            m[query[i]].Remove(idx);
 
            // Insert new location
            m[query[i]].Add(arr.Length + i);
        }
 
        // List of Tuple to store index
        // value pair
        List<Tuple<int, int> > v
            = new List<Tuple<int, int> >();
 
        // Insert all index value pair
        // into the list v
        foreach(KeyValuePair<int, HashSet<int> > x in m)
        {
            foreach(int y in x.Value)
            {
                v.Add(Tuple.Create(y, x.Key));
            }
        }
 
        // Sort v in increasing order
        // of the index
        v.Sort((a, b) => a.Item1 - b.Item1);
 
        // Print array
        foreach(Tuple<int, int> entry in v)
        {
            Console.Write(entry.Item2 + " ");
        }
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 1, 3, 1, 3 };
        int[] query = { 3, 1 };
 
        SendToLast(arr, query);
    }
}
 
// This


Javascript




// JavaScript implementation of the approach
 
// Function to print the array after
// performing the given operations
function sendToLast(arr, query) {
      // Stores index of present integers in a Map
      let m = new Map();
 
      // Loop to insert indices into the Map
      for (let i = 0; i < arr.length; i++) {
        if (!m.has(arr[i])) {
              m.set(arr[i], new Set());
        }
        m.get(arr[i]).add(i);
      }
 
      // Loop to iterate the query array
      for (let i = 0; i < query.length; i++) {
        // Erase the index of current element from the Map
        let index = m.get(query[i]).values().next().value;
        m.get(query[i]).delete(index);
 
        // Insert new location
        m.get(query[i]).add(arr.length + i);
      }
 
    // Array to store index value pairs
    let v = [];
 
    // Insert all index value pairs into the array v
    for (let [key, value] of m) {
        for (let y of value) {
              v.push([y, key]);
        }
    }
 
    // Sort v in increasing order of the index
    v.sort((a, b) => a[0] - b[0]);
 
    // Print array
    let result = "";
    for (let i = 0; i < v.length; i++) {
          result += v[i][1] + " ";
    }
    console.log(result);
}
 
// Driver code
let arr = [1, 3, 1, 3];
let query = [3, 1];
 
sendToLast(arr, query);
 
// This code is contributed by lokesh.


 
 

Output

1 3 3 1 

Time Complexity: O(Q * log N)
Auxiliary Space: O(N) 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads