Queries to find minimum swaps required to sort given array with updates
Last Updated :
04 May, 2021
Given a sorted array arr[] of size N and an array Q[][] having queries in the form of {x, y}. In each query {x, y}, update the given array by incrementing the value arr[x] by y. The task is to find the minimum number of swaps required to sort the array obtained after performing each query in the given array individually.
Examples:
Input: arr[] = {2, 3, 4, 5, 6}, Q[][] = {{2, 8}, {3, 1}}
Output: 2 0
Explanation:
Following are the number of swaps required for each query:
Query 1: Increment arr[2] by 8. Therefore, arr[] = {2, 3, 12, 5, 6}.
To make this array sorted, shift 12 right by 2 positions.
Now arr[] = {2, 3, 5, 6, 12}. Hence, it requires 2 swaps.
Query 2: Increment arr[3] by 1. Therefore, arr[] = {2, 3, 4, 6, 6}.
The array is still sorted. Hence, it requires 0 swaps.
Input: arr[] = {2, 3, 4, 5, 6}, Q[][] = {{0, -1}, {4, -11}};
Output: 0 4
Explanation:
Following are the number of swaps required for each query:
Query 1: Increment arr[0] by -1. Therefore, arr[] = {1, 3, 4, 5, 6}.
The array is still sorted. Hence, it requires 0 swaps.
Query 2: Increment arr[4] by -11. Therefore, arr[] = {2, 3, 4, 5, -5}.
To make this array sorted, shift -5 left by 4 positions.
Now arr[] = {-5, 2, 3, 4, 5}. Hence, it requires 4 swaps.
Naive Approach: The simplest approach is to update the given array by incrementing the value arr[x] by y for each query {x, y}. After that, traverse the updated array and swap arr[x] to the right while arr[x] is greater than arr[x+1], incrementing x each time then swap arr[x] to the left while arr[x] is smaller than arr[x-1], decrementing x each time. Print the absolute difference between the initial and the final value of x.
Time Complexity: O(Q*N2) where N is the length of the given array and Q is the total number of queries.
Auxiliary Space: O(N)
Efficient Approach: The idea is to use Binary Search to find the minimum number of swaps required to make the given array sorted after each query. Follow the below steps to solve the problem:
- For each query {x, y}, store the value arr[x]+y in a variable newElement.
- Using Binary Search, find the index of the value present in the given array that is just smaller than or equal to the value newElement.
- If no such value can be found, print x, otherwise let that value be at index j.
- Print the absolute difference between the index i and the index j.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the position of
// the given value using binary search
int computePos(int arr[], int n,
int value)
{
// Return 0 if every value is
// greater than the given value
if (value < arr[0])
return 0;
// Return N-1 if every value is
// smaller than the given value
if (value > arr[n - 1])
return n - 1;
// Perform Binary Search
int start = 0;
int end = n - 1;
// Iterate till start < end
while (start < end) {
// Find the mid
int mid = (start + end + 1) / 2;
// Update start and end
if (arr[mid] >= value)
end = mid - 1;
else
start = mid;
}
// Return the position of
// the given value
return start;
}
// Function to return the number of
// make the array sorted
void countShift(int arr[], int n,
vector<vector<int> >& queries)
{
for (auto q : queries) {
// Index x to update
int index = q[0];
// Increment value by y
int update = q[1];
// Set newElement equals
// to x + y
int newElement = arr[index]
+ update;
// Compute the new index
int newIndex = computePos(
arr, n, newElement);
// Print the minimum number
// of swaps
cout << abs(newIndex - index)
<< " ";
}
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 2, 3, 4, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
// Given Queries
vector<vector<int> > queries
= { { 0, -1 }, { 4, -11 } };
// Function Call
countShift(arr, N, queries);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
// Function to return the position of
// the given value using binary search
static int computePos(int arr[],
int n, int value)
{
// Return 0 if every value is
// greater than the given value
if (value < arr[0])
return 0;
// Return N-1 if every value is
// smaller than the given value
if (value > arr[n - 1])
return n - 1;
// Perform Binary Search
int start = 0;
int end = n - 1;
// Iterate till start < end
while (start < end)
{
// Find the mid
int mid = (start +
end + 1) / 2;
// Update start and end
if (arr[mid] >= value)
end = mid - 1;
else
start = mid;
}
// Return the position of
// the given value
return start;
}
// Function to return the number of
// make the array sorted
static void countShift(int arr[], int n,
Vector<Vector<Integer> > queries)
{
for (Vector<Integer> q : queries)
{
// Index x to update
int index = q.get(0);
// Increment value by y
int update = q.get(1);
// Set newElement equals
// to x + y
int newElement = arr[index] + update;
// Compute the new index
int newIndex = computePos(arr, n,
newElement);
// Print the minimum number
// of swaps
System.out.print(Math.abs(newIndex -
index) + " ");
}
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = {2, 3, 4, 5, 6};
int N = arr.length;
// Given Queries
Vector<Vector<Integer> > queries =
new Vector<>();
Vector<Integer> v =
new Vector<>();
Vector<Integer> v1 =
new Vector<>();
v.add(0);
v.add(-1);
queries.add(v);
v1.add(4);
v1.add(-11);
queries.add(v1);
// Function Call
countShift(arr, N, queries);
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program for the above approach
# Function to return the position of
# the given value using binary search
def computePos(arr, n, value):
# Return 0 if every value is
# greater than the given value
if (value < arr[0]):
return 0
# Return N-1 if every value is
# smaller than the given value
if (value > arr[n - 1]):
return n - 1
# Perform Binary Search
start = 0
end = n - 1
# Iterate till start < end
while (start < end):
# Find the mid
mid = (start + end + 1) // 2
# Update start and end
if (arr[mid] >= value):
end = mid - 1
else:
start = mid
# Return the position of
# the given value
return start
# Function to return the number of
# make the array sorted
def countShift(arr, n, queries):
for q in queries:
# Index x to update
index = q[0]
# Increment value by y
update = q[1]
# Set newElement equals
# to x + y
newElement = arr[index] + update
# Compute the new index
newIndex = computePos(arr, n, newElement)
# Print the minimum number
# of swaps
print(abs(newIndex - index), end = " ")
# Driver Code
if __name__ == '__main__':
# Given array arr[]
arr = [ 2, 3, 4, 5, 6 ]
N = len(arr)
# Given Queries
queries = [ [ 0, -1 ], [4, -11 ] ]
# Function Call
countShift(arr, N, queries)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to return the position of
// the given value using binary search
static int computePos(int []arr,
int n, int value)
{
// Return 0 if every value is
// greater than the given value
if (value < arr[0])
return 0;
// Return N-1 if every value is
// smaller than the given value
if (value > arr[n - 1])
return n - 1;
// Perform Binary Search
int start = 0;
int end = n - 1;
// Iterate till start
// < end
while (start < end)
{
// Find the mid
int mid = (start +
end + 1) / 2;
// Update start and end
if (arr[mid] >= value)
end = mid - 1;
else
start = mid;
}
// Return the position of
// the given value
return start;
}
// Function to return the number of
// make the array sorted
static void countShift(int []arr, int n,
List<List<int> >
queries)
{
foreach (List<int> q in queries)
{
// Index x to update
int index = q[0];
// Increment value by y
int update = q[1];
// Set newElement equals
// to x + y
int newElement = arr[index] +
update;
// Compute the new index
int newIndex = computePos(arr, n,
newElement);
// Print the minimum number
// of swaps
Console.Write(Math.Abs(newIndex -
index) + " ");
}
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = {2, 3, 4, 5, 6};
int N = arr.Length;
// Given Queries
List<List<int> > queries =
new List<List<int>>();
List<int> v =
new List<int>();
List<int> v1 =
new List<int>();
v.Add(0);
v.Add(-1);
queries.Add(v);
v1.Add(4);
v1.Add(-11);
queries.Add(v1);
// Function Call
countShift(arr, N, queries);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for the above approach
// Function to return the position of
// the given value using binary search
function computePos(arr, n, value)
{
// Return 0 if every value is
// greater than the given value
if (value < arr[0])
return 0;
// Return N-1 if every value is
// smaller than the given value
if (value > arr[n - 1])
return n - 1;
// Perform Binary Search
var start = 0;
var end = n - 1;
// Iterate till start < end
while (start < end) {
// Find the mid
var mid = parseInt((start + end + 1) / 2);
// Update start and end
if (arr[mid] >= value)
end = mid - 1;
else
start = mid;
}
// Return the position of
// the given value
return start;
}
// Function to return the number of
// make the array sorted
function countShift(arr, n, queries)
{
for(var i =0; i< queries.length; i++)
{
// Index x to update
var index = queries[i][0];
// Increment value by y
var update = queries[i][1];
// Set newElement equals
// to x + y
var newElement = arr[index]
+ update;
// Compute the new index
var newIndex = computePos(
arr, n, newElement);
// Print the minimum number
// of swaps
document.write( Math.abs(newIndex - index)
+ " ");
}
}
// Driver Code
// Given array arr[]
var arr = [ 2, 3, 4, 5, 6 ];
var N = arr.length;
// Given Queries
var queries = [[ 0, -1 ], [ 4, -11 ]];
// Function Call
countShift(arr, N, queries);
</script>
Time Complexity: O(Q*N*log N)
Auxiliary Space: O(N)
Similar Reads
Minimize given operations required to sort the stream array Given an array stream of n integers in the form of a stream, the task is to find the minimum number of operations that are required to sort the stream (increasing order) following the below steps: In one operation you can pick up the first element and then put that element into the xth index. All th
6 min read
Minimum number of moves required to sort Array by swapping with X Given an integer array, arr[] of size N and an integer X. The task is to sort the array in increasing order in a minimum number of moves by swapping any array element greater than X with X any number of times. If it is not possible print -1. Examples: Input: arr[] = {1, 3, 4, 6, 5}, X = 2Output: 3Ex
7 min read
Minimum swap required to convert binary tree to binary search tree Given an array arr[] which represents a Complete Binary Tree i.e., if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swaps required to convert it into a Binary Search Tree.Examples: Input: arr[] = [5, 6, 7, 8, 9,
9 min read
Minimum operations required to Sort the Array using following operations Given an array arr[] of size N. Make the array arr[] sorted in non-decreasing order in the minimum number of operations where you can choose any integer x and replace elements arr[i] == x equal to 0 for, 0 ? i ? N - 1. Examples: Input: n = 3, arr[] = {3, 3, 2}Output: 1Explanation: If you choose x =
10 min read
Minimum number of swaps required to sort an array of first N number Given an array arr[] of distinct integers from 1 to N. The task is to find the minimum number of swaps required to sort the array. Example: Input: arr[] = { 7, 1, 3, 2, 4, 5, 6 } Output: 5 Explanation: i arr swap (indices) 0 [7, 1, 3, 2, 4, 5, 6] swap (0, 3) 1 [2, 1, 3, 7, 4, 5, 6] swap (0, 1) 2 [1,
5 min read
Number of subarrays required to be rearranged to sort the given array Given an array arr[] consisting of the first N natural numbers, the task is to find the minimum number of subarrays required to be rearranged such that the resultant array is sorted. Examples: Input: arr[] = {2, 1, 4, 3, 5}Output: 1Explanation:Operation 1: Choose the subarray {arr[0], arr[3]}, i.e.
6 min read