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
#include <bits/stdc++.h>
using namespace std;
void sendToLast(vector< int > arr,
vector< int > query)
{
unordered_map< int , set< int > > m;
for ( int i = 0; i < arr.size(); i++) {
m[arr[i]].insert(i);
}
for ( int i = 0; i < query.size(); i++) {
m[query[i]].erase(*m[query[i]].begin());
m[query[i]].insert(arr.size() + i);
}
vector<pair< int , int > > v;
for ( auto x : m) {
for ( auto y : x.second) {
v.push_back({ y, x.first });
}
}
sort(v.begin(), v.end());
for ( int i = 0; i < v.size(); i++) {
cout << v[i].second << " " ;
}
}
int main()
{
vector< int > arr{ 1, 3, 1, 3 };
vector< int > query{ 3, 1 };
sendToLast(arr, query);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void sendToLast( int [] arr, int [] query)
{
Map<Integer, Set<Integer> > m = new HashMap<>();
for ( int i = 0 ; i < arr.length; i++) {
m.computeIfAbsent(arr[i], k -> new HashSet<>())
.add(i);
}
for ( int i = 0 ; i < query.length; i++) {
m.get(query[i]).remove(
m.get(query[i]).iterator().next());
m.get(query[i]).add(arr.length + i);
}
List<Map.Entry<Integer, Integer> > v
= new ArrayList<>();
for (Map.Entry<Integer, Set<Integer> > x :
m.entrySet()) {
for ( int y : x.getValue()) {
v.add( new AbstractMap.SimpleEntry<>(
y, x.getKey()));
}
}
v.sort(Map.Entry.comparingByKey());
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);
}
}
|
Python3
def sendToLast(arr, query):
m = {}
for i in range ( len (arr)):
if arr[i] not in m:
m[arr[i]] = []
m[arr[i]].append(i)
for i in range ( len (query)):
m[query[i]] = m[query[i]][ 1 :]
m[query[i]].append( len (arr) + i)
v = []
for x in m:
for y in m[x]:
v.append([y, x])
v.sort()
for i in range ( len (v)):
print (v[i][ 1 ], end = " " )
arr = [ 1 , 3 , 1 , 3 ]
query = [ 3 , 1 ]
sendToLast(arr, query)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
static void SendToLast( int [] arr, int [] query)
{
Dictionary< int , HashSet< int > > m
= new Dictionary< int , HashSet< int > >();
for ( int i = 0; i < arr.Length; i++) {
if (!m.ContainsKey(arr[i])) {
m[arr[i]] = new HashSet< int >();
}
m[arr[i]].Add(i);
}
for ( int i = 0; i < query.Length; i++) {
int idx = m[query[i]].First();
m[query[i]].Remove(idx);
m[query[i]].Add(arr.Length + i);
}
List<Tuple< int , int > > v
= new List<Tuple< int , int > >();
foreach (KeyValuePair< int , HashSet< int > > x in m)
{
foreach ( int y in x.Value)
{
v.Add(Tuple.Create(y, x.Key));
}
}
v.Sort((a, b) => a.Item1 - b.Item1);
foreach (Tuple< int , int > entry in v)
{
Console.Write(entry.Item2 + " " );
}
}
static public void Main()
{
int [] arr = { 1, 3, 1, 3 };
int [] query = { 3, 1 };
SendToLast(arr, query);
}
}
|
Javascript
function sendToLast(arr, query) {
let m = new 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);
}
for (let i = 0; i < query.length; i++) {
let index = m.get(query[i]).values().next().value;
m.get(query[i]). delete (index);
m.get(query[i]).add(arr.length + i);
}
let v = [];
for (let [key, value] of m) {
for (let y of value) {
v.push([y, key]);
}
}
v.sort((a, b) => a[0] - b[0]);
let result = "" ;
for (let i = 0; i < v.length; i++) {
result += v[i][1] + " " ;
}
console.log(result);
}
let arr = [1, 3, 1, 3];
let query = [3, 1];
sendToLast(arr, query);
|
Time Complexity: O(Q * log N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
08 Feb, 2023
Like Article
Save Article