Open In App

Queries to find minimum swaps required to sort given array with updates

Last Updated : 04 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. For each query {x, y}, store the value arr[x]+y in a variable newElement.
  2. 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.
  3. If no such value can be found, print x, otherwise let that value be at index j.
  4. 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>


Output: 

0 4

 

Time Complexity: O(Q*N*log N)
Auxiliary Space: O(N)



Similar Reads

Count swaps required to sort an array using Insertion Sort
Given an array A[] of size N (1 ≤ N ≤ 105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm. Examples: Input: A[] = {2, 1, 3, 1, 2} Output: 4 Explanation: Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Count = 1. Step 3: arr[2] stays in its initial posi
15 min read
Minimum adjacent swaps required to Sort Binary array
Given a binary array, task is to sort this binary array using minimum swaps. We are allowed to swap only adjacent elements Examples: Input : [0, 0, 1, 0, 1, 0, 1, 1] Output : 3 1st swap : [0, 0, 1, 0, 0, 1, 1, 1] 2nd swap : [0, 0, 0, 1, 0, 1, 1, 1] 3rd swap : [0, 0, 0, 0, 1, 1, 1, 1] Input : Array = [0, 1, 0, 1, 0] Output : 3Recommended : Please tr
9 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, 2, 3, 7, 4, 5, 6] swap (3, 4) 3 [1, 2, 3, 4, 7, 5
5 min read
Minimum number of swaps required to sort an array
Given an array of N distinct elements, find the minimum number of swaps required to sort the array. Examples:  Input: {4, 3, 2, 1}Output: 2Explanation: Swap index 0 with 3 and 1 with 2 to form the sorted array {1, 2, 3, 4} Input: {1, 5, 4, 3, 2}Output: 2 Recommended PracticeMinimum Swaps to SortTry It!Approach: To solve the problem follow the below
31 min read
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted array by above swap condition then print not possib
14 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 queries on the given Array and print the result accordi
23 min read
Queries to find the minimum index in a range [L, R] having at least value X with updates
Given an array arr[] consisting of N integers and an array Queries[] consisting of Q queries of the type {X, L, R} to perform following operations: If the value of X is 1, then update the array element at Xth index to L.Otherwise, find the minimum index j in the range [L, R] such that arr[j] ? X. If no such j exists, then print "-1".Examples: Input
22 min read
Array range queries to find the number of perfect square elements with updates
Given an array arr[] of N integers, the task is to perform the following two queries: query(start, end): Print the number of perfect square numbers in the sub-array from start to endupdate(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x Note: 0 based indexing is followed in the below example. Example: Input: arr =
30 min read
Queries to find the Lower Bound of K from Prefix Sum Array with updates using Fenwick Tree
Given an array A[ ] consisting of non-negative integers and a matrix Q[ ][ ] consisting of queries of the following two types: (1, l, val): Update A[l] to A[l] + val.(2, K): Find the lower_bound of K in the prefix sum array of A[ ]. If the lower_bound does not exist, print -1. The task for each query of the second type is to print the index of the
14 min read
Queries to find the first array element exceeding K with updates
Given an array arr[] of size N and a 2D array Q[][] consisting of queries of the following two types: 1 X Y: Update the array element at index X with Y.2 K: Print the position of the first array element greater than or equal to K. If there is no such index, then print -1. Examples: Input : arr[] = { 1, 3, 2, 4, 6 }, Q[][] = {{2, 5}, {1, 3, 5}, {2,
19 min read