Open In App

Queries to search for an element in an array and modify the array based on given conditions

Last Updated : 12 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers and an integer X, the task is to print the array after performing X queries denoted by an array operations[]. The task for each query is as follows:

  • If the array contains the integer operations[i], reverse the subarray starting from the index at which operations[i] is found, to the end of the array.
  • Otherwise, insert operations[i] to the end of the array.

Examples:

Input: arr[] = {1, 2, 3, 4}, X = 3, operations[] = {12, 2, 13}
Output: 1 12 4 3 2
Explanation: 
Query 1: arr[] does not contain 12. Therefore, append it to the last. Therefore, arr[] = {1, 2, 3, 4, 12}. 
Query 2: arr[] contains 2 at index 1. Therefore, reverse the subarray {arr[1], arr[4]}. Therefore, arr[] = {1, 12, 4, 3, 2}. 
Query 3: arr[] does not contain 13. Therefore, append it to the last. Therefore, arr[] = {1, 12, 4, 3, 2, 13}.

Input: arr[] = {1, 1, 12, 6}, X = 2, operations[] = {1, 13}
Output: 1 12 4 3 2

Approach: The simplest approach is that for each query search the whole array to check if the concerned integer is present or not. If present at an index i and the current size of the array is N, then reverse the subarray {arr[i], … arr[N – 1]} . Otherwise, insert the searched element at the end of the array. Follow the steps below to solve the problem:

  1. Create a function to linearly search for the index of an element in an array.
  2. Now for each query, if the given element is not present in the given array, append that to the end of the array.
  3. Otherwise, if it is present at any index i, reverse the subarray starting from index i up to the end.
  4. After completing the above steps, print the resultant array.

Below is the implementation for the above approach:

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to reverse the subarray
// over the range [i, r]
void rev(vector<int> &arr, int l, int r)
{
     
    // Iterate over the range [l, r]
    while (l < r)
    {
        int tmp = arr[l];
        arr[l] = arr[r];
        arr[r] = tmp;
        l++;
        r--;
    }
}
 
// Function that perform the given
// queries for the given array
void doOperation(vector<int> &arr, int o)
{
     
    // Search for the element o
    int ind = -1;
 
    // Current size of the array
    int n = arr.size();
 
    for(int i = 0; i < n; i++)
    {
         
        // If found, break out of loop
        if (arr[i] == o)
        {
            ind = i;
            break;
        }
    }
 
    // If not found, append o
    if (ind == -1)
        arr.push_back(o);
 
    // Otherwise, reverse the
    // subarray arr[ind] to arr[n - 1]
    else
        rev(arr, ind, n - 1);
}
 
// Function to print the elements
// in the vector arr[]
void print(vector<int> &arr)
{
     
    // Traverse the array arr[]
    for(int x : arr)
    {
         
        // Print element
        cout << x << " ";
    }
}
 
// Function to perform operations
void operations(vector<int> &queries,
                vector<int> &arr)
{
    for(auto x : queries)
        doOperation(arr, x);
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 2, 3, 4 };
    int x = 3;
 
    // Given queries
    vector<int> queries({ 12, 2, 13 });
 
    // Add elements to the vector
    vector<int> arr1;
 
    for(int z : arr)
        arr1.push_back(z);
 
    // Perform queries
    operations(queries, arr1);
 
    // Print the resultant array
    print(arr1);
}
 
// This code is contributed by SURENDRA_GANGWAR


Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function that perform the given
    // queries for the given array
    static void doOperation(
        ArrayList<Integer> arr, int o)
    {
 
        // Search for the element o
        int ind = -1;
 
        // Current size of the array
        int n = arr.size();
 
        for (int i = 0; i < n; i++) {
 
            // If found, break out of loop
            if (arr.get(i) == o) {
                ind = i;
                break;
            }
        }
 
        // If not found, append o
        if (ind == -1)
            arr.add(o);
 
        // Otherwise, reverse the
        // subarray arr[ind] to arr[n - 1]
        else
            reverse(arr, ind, n - 1);
    }
 
    // Function to reverse the subarray
    // over the range [i, r]
    static void reverse(
        ArrayList<Integer> arr, int l,
        int r)
    {
        // Iterate over the range [l, r]
        while (l < r) {
            int tmp = arr.get(l);
            arr.set(l, arr.get(r));
            arr.set(r, tmp);
            l++;
            r--;
        }
    }
 
    // Function to print the elements
    // in the ArrayList arr[]
    static void print(ArrayList<Integer> arr)
    {
        // Traverse the array arr[]
        for (int x : arr) {
 
            // Print element
            System.out.print(x + " ");
        }
    }
 
    // Function to perform operations
    static void operations(
        int queries[],
        ArrayList<Integer> arr)
    {
        for (int x : queries)
            doOperation(arr, x);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 1, 2, 3, 4 };
        int x = 3;
 
        // Given queries
        int queries[] = { 12, 2, 13 };
 
        // Add elements to the arraylist
        ArrayList<Integer> arr1
            = new ArrayList<>();
 
        for (int z : arr)
            arr1.add(z);
 
        // Perform queries
        operations(queries, arr1);
 
        // Print the resultant array
        print(arr1);
    }
}


Python3




# Python3 program for
# the above approach
 
# Function to reverse the
# subarray over the range
# [i, r]
def rev(arr, l, r):
 
    # Iterate over the
    # range [l, r]
    while (l < r):
        arr[l], arr[r] = (arr[r],
                          arr[l])
        l += 1
        r -= 1
 
# Function that perform the given
# queries for the given array
def doOperation(arr, o):
 
    # Search for the
    # element o
    ind = -1
 
    # Current size of
    # the array
    n = len(arr)
 
    for i in range(n):
 
        # If found, break out
        # of loop
        if (arr[i] == o):
 
            ind = i
            break
 
    # If not found, append o
    if (ind == -1):
        arr.append(o)
 
    # Otherwise, reverse the
    # subarray arr[ind] to
    # arr[n - 1]
    else:
        rev(arr,
            ind, n - 1)
 
# Function to print the
# elements in the vector
# arr[]
def print_array(arr):
 
    # Traverse the
    # array arr[]
    for x in arr:
 
        # Print element
        print(x, end = " ")
 
# Function to perform
# operations
def operations(queries, arr):
 
    for x in queries:
        doOperation(arr, x)
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [1, 2, 3, 4]
    x = 3
 
    # Given queries
    queries = [12, 2, 13]
 
    # Add elements to the vector
    arr1 = []
 
    for z in arr:
        arr1.append(z)
 
    # Perform queries
    operations(queries, arr1)
 
    # Print the resultant array
    print_array(arr1)
 
# This code is contributed by Chitranayal


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function that perform the given
// queries for the given array
static void doOperation(List<int> arr, int o)
{
     
    // Search for the element o
    int ind = -1;
 
    // Current size of the array
    int n = arr.Count;
 
    for(int i = 0; i < n; i++)
    {
         
        // If found, break out of loop
        if (arr[i] == o)
        {
            ind = i;
            break;
        }
    }
 
    // If not found, append o
    if (ind == -1)
        arr.Add(o);
 
    // Otherwise, reverse the
    // subarray arr[ind] to arr[n - 1]
    else
        reverse(arr, ind, n - 1);
}
 
// Function to reverse the subarray
// over the range [i, r]
static void reverse(List<int> arr, int l,
                                   int r)
{
     
    // Iterate over the range [l, r]
    while (l < r)
    {
        int tmp = arr[l];
        arr[l] = arr[r];
        arr[r] =  tmp;
        l++;
        r--;
    }
}
 
// Function to print the elements
// in the List []arr
static void print(List<int> arr)
{
     
    // Traverse the array []arr
    foreach(int x in arr)
    {
 
        // Print element
        Console.Write(x + " ");
    }
}
 
// Function to perform operations
static void operations(int []queries,
                       List<int> arr)
{
    foreach(int x in queries)
        doOperation(arr, x);
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 1, 2, 3, 4 };
    //int x = 3;
 
    // Given queries
    int []queries = { 12, 2, 13 };
 
    // Add elements to the arraylist
    List<int> arr1 = new List<int>();
 
    foreach (int z in arr)
        arr1.Add(z);
 
    // Perform queries
    operations(queries, arr1);
 
    // Print the resultant array
    print(arr1);
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// Javascript program for the above approach
 
// Function that perform the given
// queries for the given array
function doOperation(arr, o)
{
     
    // Search for the element o
    let ind = -1;
 
    // Current size of the array
    let n = arr.length;
 
    for(let i = 0; i < n; i++)
    {
         
        // If found, break out of loop
        if (arr[i] == o)
        {
            ind = i;
            break;
        }
    }
 
    // If not found, append o
    if (ind == -1)
        arr.push(o);
 
    // Otherwise, reverse the
    // subarray arr[ind] to arr[n - 1]
    else
        reverse(arr, ind, n - 1);
}
 
// Function to reverse the subarray
// over the range [i, r]
function reverse(arr, l, r)
{
     
    // Iterate over the range [l, r]
    while (l < r)
    {
        let tmp = arr[l];
        arr[l] = arr[r];
        arr[r] = tmp;
        l++;
        r--;
    }
}
 
// Function to print the elements
// in the ArrayList arr[]
function print(arr)
{
    document.write(arr.join(" "));
}
 
// Function to perform operations   
function operations(queries, arr)
{
    for(let x = 0; x < queries.length; x++)
        doOperation(arr, queries[x]);
}
 
// Driver Code
let arr = [ 1, 2, 3, 4 ];
let x = 3;
 
// Given queries
let queries = [ 12, 2, 13 ];
 
// Perform queries
operations(queries, arr);
 
// Print the resultant array
print(arr);
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

1 12 4 3 2 13 

Time Complexity: O(N*X) where N is the size of the given array and X is the number of queries.
Auxiliary Space: O(N)



Similar Reads

Find the Array element after Q queries based on the given conditions
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 th
10 min read
Modify a given array by replacing each element with the sum or product of their digits based on a given condition
Given an array arr[] consisting of N integers, the task is to modify the array elements after performing only one of the following operations on each array elements: If the count of even digits is greater than the count of odd digits in an array element, then update that element to the sum of all the digits of that element.Otherwise, update that el
8 min read
Range sum queries based on given conditions
Given an array arr[] of N integers and matrix Queries[][] consisting of Q queries of the form {m, a, b}. For each query the task is to find the sum of array elements according to the following conditions: If m = 1: Find the sum of the array elements in the range [a, b].If m = 2: Rearrange the array elements in increasing order and find the sum of t
17 min read
Count of moves to escape given Matrix from given position based on given conditions
Given an N x M matrix mat[][] where initially we are standing at the cell with index (i, j), the task is to find the number of operations required to escape the given matrix where at each operation mat[x][y] can be reached from mat[i][j] such that x represents the count of 0's in the binary representation of mat[i][j] and y represents the count of
9 min read
Reduce the given Array of [1, N] by rotating left or right based on given conditions
Given a sorted array arr[] of the first N Natural Numbers and an integer X, the task is to print the last remaining element after performing the below operations (N - 1) times: If the value of X is 1, then right rotate the array by 1 unit and delete the last element.If the value of X is 2, then left rotate the array by 1 unit and delete the first e
6 min read
Minimum steps to reach a given index in the Array based on given conditions
Given an array arr[ ] of size N consisting of integers -1, 0, 1 only and an array q[ ] consisting of queries. In the array arr[ ], -1 signifies that any index to the left of it is reachable and 1 signifies that any index to the right of it is reachable from that index. The index in a particular query is not directly reachable but all other indices
10 min read
Generate a String from given Strings P and Q based on the given conditions
Given two strings P and Q, the task is to generate a string S satisfying the following conditions: Find S such that P is rearranged and Q is a substring in it.All the characters before Q in S should be smaller than or equal to the first character in Q and in lexicographic order.The rest of the characters should be present after Q in lexicographic o
7 min read
Modify given array by reducing each element by its next smaller element
Given an array arr[] of length N, the task is to modify the given array by replacing each element of the given array by its next smaller element, if possible. Print the modified array as the required answer. Examples: Input: arr[] = {8, 4, 6, 2, 3}Output: 4 2 4 2 3Explanation: The operations can be performed as follows: For arr[0], arr[1] is the ne
11 min read
Maximize value of a pair from two given arrays based on given conditions
Given two arrays A[] and B[] consisting of N integers and an integer K, the task is to find the maximum value of B[i] + B[j] + abs(A[i] - A[j]) by choosing any pair (i, j) such that abs(A[i] - A[j]) ? K. Examples: Input: A[] = {5, 6, 9, 10}, B[] = {3, 0, 10, -10}, K = 1Output: 4Explanation:Only two pairs can be chosen, i.e. (0, 1) and (2, 3), becau
17 min read
Minimum time required to print given string from a circular container based on given conditions
Given a circular container consisting of lowercase alphabets from 'a' to 'z', a pointer pointing initially at alphabet 'a', and a string str, the task is to find the minimum time required to print the given string str from the circular container, based on following operations that can be performed on every character: Move the pointer one character
6 min read
Practice Tags :