 Open in App
Not now

# Find the Array element after Q queries based on the given conditions

• Difficulty Level : Medium
• Last Updated : 23 Feb, 2023

Given an array arr[] of length N and Q queries of 3 types (1, 2, 3) whose operations are as follows:

• Type 1: query has input as 1 and the task is to reverse the array.
• Type 2: query has input as (2 x) and the task to find the index of x in the result array.
• Type 3: query has input as (3 x y) and the task is to swap the elements at index x and y in the array.

The task is to print the result for the query of type 2.

Examples:

Input: N = 5, arr[] = {3, 7, 8, 1, 33}, Q = 4, Queries[][] = {{1}, {2, 8}, {3, 2, 4}, {2, 1}
Output: 2 1
Explanation: Process query wise first is 1 so reverse the list [33, 1, 8, 7, 3], Second query 2 8 so find index of element 8 which is 2, third query is 3 2 4 so swap 2nd and 4th index new array=[33, 1, 3, 7, 8] now the last query is 2 1 so find index of element 1 which is 1 so output 2 1.

Input: N = 6, arr[] = {6, 33, 9, 22, 45, 4}, Q = 5, Queries[][] = {{1}, {3, 0, 4}, {2, 33}, {1}, {2, 9}}
Output: 0 2

Approach: The given problem can be solved based on the following assumptions for each query:

• Use a variable flag =1 and for every query of type 1, multiply flag*-1 so that for negative it indicates a reversal of list and manipulates the calculation in reverse order rather than directly reversing the array and this way reduces time complexity.
• Now for the query of type 3 x y, use the map data structure to store index and element as key and value pairs and directly interchange the values in O(1).
• Finally for the query of type 2 x directly fetch the index.

Follow the steps below to solve the problem:

• Initialize a map mp = {} to store the element and its index in the array as key-value pair.
• Initialize the variable flag as 1 to keep the track of the count of the number of times the array is reversed.
• Iterate over the range [0, Q) using the variable i and perform the following tasks:
• First, check for the type of query while taking each query as input.
• For type 1 query instead of reversing manually which will increase time complexity, change the sign of the variable flag to denote array is normal or reversed.
• For type 2 query, find the index of the given value from the map, and if the array is not reversed then print the value of m[x] as the result. Otherwise, print the value of (N – m[x] – 1).
• For type 3 query, first, find the values at given index and then swap the value and index in the list and map respectively.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `// Function to perform the given queries` `// and print the result accordingly` `#include` `using` `namespace` `std;`   `void` `arrayManipulation(``int` `n,vector<``int``> arr,``int` `q,vector> qarr){`   `    ``// Stores the index value pair` `    ``unordered_map<``int``,``int``>mp;` `    ``vector<``int``>ans;`   `    ``// Flag to indicate reversal` `    ``int` `flg = 1;` `    ``for``(``int` `i=0;ia = qarr[i];`   `        ``// Type 1 flag multiplied -1` `        ``if``(a == 1)` `            ``flg *= -1;` `            `  `        ``// Type 2 query taking index` `        ``// value acc. to flag sign` `        ``else` `if``(a == 2){` `            ``int` `x = a;` `            ``if``(flg == -1)` `                ``ans.push_back(n-mp[x]-1);` `            ``else` `                ``ans.push_back(mp[x]);` `        ``}` `                `  `        ``// Type 3 query swapping value` `        ``// directly in map` `        ``else``{` `            ``int` `x = a;` `            ``int` `y = a;`   `            ``// Stores the value to swap` `            ``// and update the array` `            ``int` `x1 = a;` `            ``int` `y1 = a;` `            ``if``(flg == -1){` `                ``y = n-y-1;` `                ``x = n-x-1;` `            ``}`   `            ``// Value swapped and store` `            ``// value to swap and update` `            ``// the map` `            ``y = arr[y];` `            ``x = arr[x];`   `            ``// Index swapped` `            ``swap(arr[x1],arr[y1]);` `            ``swap(mp[x],mp[y]);` `        ``}` `    ``}`   `    ``// Print the result for queries` `    ``for``(``auto` `x:ans){` `        ``cout< arr = {6, 33, 9, 22, 45, 4};` `int` `Q = 5;` `vector>Queries = {{1}, {3, 0, 4}, {2, 33}, {1}, {2, 9}};` `  `  `// Function Call` `arrayManipulation(N, arr, Q, Queries);`   `}`   `// This code is contributed by shinjanpatra`

## Java

 `import` `java.util.ArrayList;` `import` `java.util.Arrays;` `import` `java.util.HashMap;` `import` `java.util.List;`   `class` `Main {`   `    ``// Function to perform the given queries` `    ``// and print the result accordingly` `    ``public` `static` `void` `arrayManipulation(``int` `n, List arr, ` `                                         ``int` `q, List> qarr) {`   `        ``// Stores the index value pair` `        ``HashMap mp = ``new` `HashMap();` `        ``ArrayList ans = ``new` `ArrayList();`   `        ``// Flag to indicate reversal` `        ``int` `flg = ``1``;` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``mp.put(arr.get(i), i);` `        ``}`   `        ``// Processing each query` `        ``for` `(``int` `i = ``0``; i < q; i++) {` `            ``List a = qarr.get(i);`   `            ``// Type 1 flag multiplied -1` `            ``if` `(a.get(``0``) == ``1``)` `                ``flg *= -``1``;`   `            ``// Type 2 query taking index` `            ``// value acc. to flag sign` `            ``else` `if` `(a.get(``0``) == ``2``) {` `                ``int` `x = a.get(``1``);` `                ``if` `(flg == -``1``)` `                    ``ans.add(n - mp.get(x) - ``1``);` `                ``else` `                    ``ans.add(mp.get(x));` `            ``}`   `            ``// Type 3 query swapping value` `            ``// directly in map` `            ``else` `{` `                ``int` `x = a.get(``1``);` `                ``int` `y = a.get(``2``);`   `                ``// Stores the value to swap` `                ``// and update the array` `                ``int` `x1 = a.get(``1``);` `                ``int` `y1 = a.get(``2``);` `                ``if` `(flg == -``1``) {` `                    ``y = n - y - ``1``;` `                    ``x = n - x - ``1``;` `                ``}`   `                ``// Value swapped and store` `                ``// value to swap and update` `                ``// the map` `                ``y = arr.get(y);` `                ``x = arr.get(x);`   `                ``// Index swapped` `                ``int` `temp = arr.get(x1);` `                ``arr.set(x1, arr.get(y1));` `                ``arr.set(y1, temp);` `                ``mp.put(x, mp.get(y));` `                ``mp.put(y, temp);` `            ``}` `        ``}`   `        ``// Print the result for queries` `        ``for` `(``int` `x : ans) {` `          ``if``(x==-``1``) x = ``0``;` `            ``System.out.print(x + ``" "``);` `        ``}` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``int` `N = ``6``;` `        ``List arr = ` `          ``new` `ArrayList(Arrays.asList(``6``, ``33``, ``9``, ``22``, ``45``, ``4``));` `        ``int` `Q = ``5``;` `        ``List> Queries = ``new` `ArrayList>();` `        ``Queries.add(``new` `ArrayList(Arrays.asList(``1``)));` `        ``Queries.add(``new` `ArrayList(Arrays.asList(``3``, ``0``, ``4``)));` `        ``Queries.add(``new` `ArrayList(Arrays.asList(``2``, ``33``)));` `        ``Queries.add(``new` `ArrayList(Arrays.asList(``1``)));` `        ``Queries.add(``new` `ArrayList(Arrays.asList(``2``, ``9``)));` `  `  `        ``// Function Call` `        ``arrayManipulation(N, arr, Q, Queries);` `    ``}` `}`

## Python3

 `# Python program for the above approach`   `# Function to perform the given queries` `# and print the result accordingly` `def` `arrayManipulation(n, arr, q, qarr):`   `    ``# Stores the index value pair` `    ``mp ``=` `{}` `    ``ans ``=` `[]`   `    ``# Flag to indicate reversal` `    ``flg ``=` `1` `    ``for` `i ``in` `range``(n):` `        ``mp[arr[i]] ``=` `i`   `    ``# Processing each query` `    ``for` `i ``in` `range``(q):` `        ``a ``=` `qarr[i]`   `        ``# Type 1 flag multiplied -1` `        ``if``(a[``0``] ``=``=` `1``):` `            ``flg ``*``=` `-``1` `            `  `        ``# Type 2 query taking index` `        ``# value acc. to flag sign` `        ``elif``(a[``0``] ``=``=` `2``):` `            ``x ``=` `a[``1``]` `            ``if``(flg ``=``=` `-``1``):` `                ``ans.append(n``-``mp[x]``-``1``)` `            ``else``:` `                ``ans.append(mp[x])` `                `  `        ``# Type 3 query swapping value` `        ``# directly in map` `        ``else``:` `            ``x ``=` `a[``1``]` `            ``y ``=` `a[``2``]`   `            ``# Stores the value to swap` `            ``# and update the array` `            ``x1 ``=` `a[``1``]` `            ``y1 ``=` `a[``2``]` `            ``if``(flg ``=``=` `-``1``):` `                ``y ``=` `n``-``y``-``1` `                ``x ``=` `n``-``x``-``1`   `            ``# Value swapped and store` `            ``# value to swap and update` `            ``# the map` `            ``y ``=` `arr[y]` `            ``x ``=` `arr[x]`   `            ``# Index swapped` `            ``arr[x1], arr[y1] ``=` `arr[y1], arr[x1]` `            ``mp[x], mp[y] ``=` `mp[y], mp[x]`   `    ``# Print the result for queries` `    ``print``(``*``ans)`     `# Driver Code` `N ``=` `6` `arr ``=` `[``6``, ``33``, ``9``, ``22``, ``45``, ``4``]` `Q ``=` `5` `Queries ``=` `[[``1``], [``3``, ``0``, ``4``], [``2``, ``33``], [``1``], [``2``, ``9``]]`   `# Function Call` `arrayManipulation(N, arr, Q, Queries)`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `Program` `{` `  ``static` `void` `ArrayManipulation(``int` `n, ``int``[] arr, ``int` `q, ``int``[][] qarr)` `  ``{`   `    ``// Stores the index value pair` `    ``Dictionary<``int``, ``int``> mp = ``new` `Dictionary<``int``, ``int``>();` `    ``List<``int``> ans = ``new` `List<``int``>();`   `    ``// Flag to indicate reversal` `    ``int` `flg = 1;` `    ``for` `(``int` `i = 0; i < n; i++)` `    ``{` `      ``mp[arr[i]] = i;` `    ``}`   `    ``// Processing each query` `    ``for` `(``int` `i = 0; i < q; i++)` `    ``{` `      ``int``[] a = qarr[i];`   `      ``// Type 1 flag multiplied -1` `      ``if` `(a == 1)` `        ``flg *= -1;`   `      ``// Type 2 query taking index` `      ``// value acc. to flag sign` `      ``else` `if` `(a == 2)` `      ``{` `        ``int` `x = a;` `        ``if` `(flg == -1)` `          ``ans.Add(n - mp[x] - 1);` `        ``else` `          ``ans.Add(mp[x]);` `      ``}`   `      ``// Type 3 query swapping value` `      ``// directly in map` `      ``else` `      ``{` `        ``int` `x = a;` `        ``int` `y = a;`   `        ``// Stores the value to swap` `        ``// and update the array` `        ``int` `x1 = a;` `        ``int` `y1 = a;` `        ``if` `(flg == -1)` `        ``{` `          ``y = n - y - 1;` `          ``x = n - x - 1;` `        ``}`   `        ``// Value swapped and store` `        ``// value to swap and update` `        ``// the map` `        ``y = arr[y];` `        ``x = arr[x];`   `        ``// Index swapped` `        ``int` `temp = arr[x1];` `        ``arr[x1] = arr[y1];` `        ``arr[y1] = temp;`   `        ``int` `temp2 = mp[x];` `        ``mp[x] = mp[y];` `        ``mp[y] = temp2;` `      ``}` `    ``}`   `    ``// Print the result for queries` `    ``Console.WriteLine(``string``.Join(``" "``, ans));` `  ``}`   `  ``static` `void` `Main(``string``[] args)` `  ``{` `    ``int` `N = 6;` `    ``int``[] arr = { 6, 33, 9, 22, 45, 4 };` `    ``int` `Q = 5;` `    ``int``[][] Queries = { ``new` `int``[] { 1 }, ``new` `int``[] { 3, 0, 4 }, ``new` `int``[] { 2, 33 }, ``new` `int``[] { 1 }, ``new` `int``[] { 2, 9 } };`   `    ``// Function Call` `    ``ArrayManipulation(N, arr, Q, Queries);` `  ``}` `}`   `// This code is contributed by shivamsharma215`

## Javascript

 `// JavaScript program for the above approach`   `// Function to perform the given queries` `// and print the result accordingly` `function` `arrayManipulation(n, arr, q, qarr) {`   `    ``// Stores the index value pair` `    ``let mp = {};` `    ``let ans = [];`   `    ``// Flag to indicate reversal` `    ``let flg = 1;` `    ``for` `(let i = 0; i < n; i++) {` `        ``mp[arr[i]] = i;` `    ``}`   `    ``// Processing each query` `    ``for` `(let i = 0; i < q; i++) {` `        ``let a = qarr[i];`   `        ``// Type 1 flag multiplied -1` `        ``if` `(a == 1) {` `            ``flg *= -1;` `            `  `        ``// Type 2 query taking index` `        ``// value acc. to flag sign` `        ``} ``else` `if` `(a == 2) {` `            ``let x = a;` `            ``if` `(flg == -1) {` `                ``ans.push(n - mp[x] - 1);` `            ``} ``else` `{` `                ``ans.push(mp[x]);` `            ``}` `                `  `        ``// Type 3 query swapping value` `        ``// directly in map` `        ``} ``else` `{` `            ``let x = a;` `            ``let y = a;`   `            ``// Stores the value to swap` `            ``// and update the array` `            ``let x1 = a;` `            ``let y1 = a;` `            ``if` `(flg == -1) {` `                ``y = n - y - 1;` `                ``x = n - x - 1;` `            ``}`   `            ``// Value swapped and store` `            ``// value to swap and update` `            ``// the map` `            ``y = arr[y];` `            ``x = arr[x];`   `            ``// Index swapped` `            ``let temp = arr[x1];` `            ``arr[x1] = arr[y1];` `            ``arr[y1] = temp;`   `            ``let temp2 = mp[x];` `            ``mp[x] = mp[y];` `            ``mp[y] = temp2;` `        ``}` `    ``}`   `    ``// Print the result for queries` `    ``console.log(...ans);`   `}`   `// Driver Code` `let N = 6;` `let arr = [6, 33, 9, 22, 45, 4];` `let Q = 5;` `let Queries = [, [3, 0, 4], [2, 33], , [2, 9]];`   `// Function Call` `arrayManipulation(N, arr, Q, Queries);`   `// This code is contributed by akashish__`

Output:

`0 2`

Time Complexity: O(max(N, Q))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles