Queries to search for an element in an array and modify the array based on given conditions
Last Updated :
12 Jun, 2021
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:
- Create a function to linearly search for the index of an element in an array.
- Now for each query, if the given element is not present in the given array, append that to the end of the array.
- Otherwise, if it is present at any index i, reverse the subarray starting from index i up to the end.
- 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>
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
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read