Print Array after moving first occurrence of given element to end in given Array for Q queries
Last Updated :
08 Feb, 2023
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.
Time Complexity: O(Q * log N)
Auxiliary Space: O(N)
Similar Reads
Queries to find first occurrence of a character in a given range Given a string S of length N and an array Q[][] of dimension M Ã 3 consisting of queries of type {L, R, C}, the task is to print the first index of the character C in the range [L, R], if found. Otherwise, print -1. Examples: Input: S= "abcabcabc", Q[][] = { { 0, 3, 'a' }, { 0, 2, 'b' }, { 2, 4, 'z'
9 min read
Most frequent element in Array after replacing given index by K for Q queries Given an array arr[] of size N, and Q queries of the form {i, k} for which, the task is to print the most frequent element in the array after replacing arr[i] by k.Example : Input: arr[] = {2, 2, 2, 3, 3}, Query = {{0, 3}, {4, 2}, {0, 4}} Output: 3 2 2 First query: Setting arr[0] = 3 modifies arr[]
10 min read
Count of Ks in the Array for a given range of indices after array updates for Q queries Given an array arr[] of N integers, an integer K, and Q queries of the type as explained below: (1, L, R): If the query is of type 1, then find the number of Ks over the range [L, R].(2, P, X): If the query is of type 2, then update the array element at index P to X. The task is to perform the queri
15+ min read
Queries to increment array elements in a given range by a given value for a given number of times Given an array, arr[] of N positive integers and M queries of the form {a, b, val, f}. The task is to print the array after performing each query to increment array elements in the range [a, b] by a value val f number of times. Examples: Input: arr[] = {1, 2, 3}, M=3, Q[][] = {{1, 2, 1, 4}, {1, 3, 2
13 min read
Replace all occurrences of X by Y or add element K in Array for Q queries Given an empty array A[] & Q queries of two types 1 and 2 represented by queries1 and queries2 respectively, the task is to find the final state of the array. The queries are of the following type: If type[i]=1, insert queries1[i] (say K) to the end of the array A. The value of queries2[i] = -1
7 min read
Queries to find minimum sum of array elements from either end of an array Given an array arr[] consisting of N distinct integers and an array queries[] consisting of Q queries, the task is for each query is to find queries[i] in the array and calculate the minimum of sum of array elements from the start and end of the array up to queries[i]. Examples: Input: arr[] = {2, 3
12 min read
Queries to count occurrences of maximum array element in subarrays starting from given indices Given two arrays arr[] and q[] consisting of N integers, the task is for each query q[i] is to determine the number of times the maximum array element occurs in the subarray [q[i], arr[N - 1]]. Examples: Input: arr[] = {5, 4, 5, 3, 2}, q[] = {1, 2, 3, 4, 5}Output: 2 1 1 1 1Explanation:For the first
10 min read
Queries to search an element in an array and move it to front after every query Given an integer M which represents an array initially having numbers 1 to M. Also given is a Query array. For every query, search the number in the initial array and bring it to the front of the array. The task is to return the indexes of the searched element in the given array for every query.Exam
15 min read
Replace all occurrences of X by Y for Q queries in given Array Given an array arr[] and an 2D array query[][] consisting of queries. For each query q, replace all occurrences of query[i][0] in arr[], with query[i][1]. Examples: Input: arr[] = {2, 2, 5, 1} query = {{2, 4}, {5, 2}}Output: {4, 4, 2, 1}Explanation: Following are the operations performed in the give
7 min read