Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same
Next article icon

Sort elements of an array A[] placed on a number line by shifting i-th element to (i + B[i])th positions minimum number of times

Last Updated : 22 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays A[] and B[] consisting of N positive integers such that each array element A[i] is placed at the ith position on the number line, the task is to find the minimum number of operations required to sort the array elements arranged in the number line. In each operation any array element A[i] can move to the position (i + B[i])th on the number line. Two or more elements can come to the same number line.

Examples:

Input: A[] = {2, 1, 4, 3}, B[] = {4, 1, 2, 4}
Output: 5
Explanation:

Initially array 2, 1, 4, 3 are placed on the number line at 0, 1, 2, 3 positions respectively.
Operation 1: Move arr[0](= 2) by move[0](= 4). Now the element are arranged as {1, 4, 3, 2} at indices on the number line is {1, 2, 3, 4} respectively.
Operation 2: Move arr[3](= 3) by move[3](= 4). Now the element are arranged as {1, 4, 2, 3} at indices on the number line is {1, 2, 4, 7} respectively.
Operation 3: Move arr[2](= 4) move[2](= 2). Now the element are arranged as {1, 2, 4, 3} at indices on the number line is {1, 4, 4, 7} respectively.
Operation 4: Move arr[3](= 4) move[2](= 2). Now the element are arranged as {1, 2, 3, 4} at indices on the number line is {1, 4, 6, 7} respectively.
Operation 5: In first operation move arr[0](= 2) i.e., 2 by move[0](= 4). Now the element are arranged as {1, 4, 3, 2} at indices on the number line is {1, 4, 7, 8} respectively.

Input: A[] = {1, 2, 3, 4}, B[] = {4, 1, 2, 4}
Output: 0

Approach: The given problem can be solved using the Greedy Approach by moving the greater element one by one to its next possible index and then find the minimum of all the operations required. Follow the steps below to solve the given problem:

  • Initialize a 2D vectors, say arr[] such that each ith element represents the element, corresponding moves, and the current position as {arr[i], A[i], current_position}.
  • Sort the array arr[] in ascending order.
  • Initialize two variables, say cnt and f, and Mark count as 0 and flag as 1 to store the number of required operations.
  • Iterate until F is not equal to 1 and perform the following steps:
    • Update the value of F equals 0.
    • For each element in vector arr[] and If the value of arr[i][2] is at least arr[i + 1][2], then increment the count by 1, f = 1 and the current position of the (i + 1)th element i.e., (arr[i + 1][2]) by arr[i + 1][1].
  • After completing the above steps, print the value of count as the result.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find minimum number of // operations required to sort N array // elements placed on a number line int minHits(int arr[], int move[],             int n) {     // Stores the value of     // {A[i], B[i], current position}     vector<vector<int> > V(n, vector<int>(3));      // Populate the current position     // every elements     for (int i = 0; i < n; i++) {         V[i] = { arr[i], move[i], i };     }      // Sort the vector V     sort(V.begin(), V.end());      // Stores the total number of     // operations required     int cnt = 0;     int f = 1;      // Iterate until f equals 1     while (f == 1) {          // Update f equals zero         f = 0;          // Traverse through vector         // and check for i and i+1         for (int i = 0; i < n - 1; i++) {              // If current position of             // i is at least current             // position of i+1             if (V[i][2] >= V[i + 1][2]) {                  // Increase the current                 // position of V[i+1][2]                 // by V[i+1][1]                 V[i + 1][2] += V[i + 1][1];                  // Increment the count                 // of operations                 cnt++;                  // Update the flag equals                 // to 1                 f = 1;                  // Break the for loop                 break;             }         }     }      // Return the total operations     // required     return cnt; }  // Driver Code int main() {     int A[] = { 2, 1, 4, 3 };     int B[] = { 4, 1, 2, 4 };     int N = sizeof(A) / sizeof(A[0]);      cout << minHits(A, B, N);      return 0; } 
Java
// Java program for the above approach import java.util.Arrays;     class GFG {    // Function to find minimum number of   // operations required to sort N array   // elements placed on a number line   public static int minHits(int arr[], int move[],                             int n)   {     // Stores the value of     // {A[i], B[i], current position}     int[][] V = new int[n][3];      // Populate the current position     // every elements     for (int i = 0; i < n; i++) {       V[i][0] = arr[i];       V[i][1] = move[i];       V[i][2] = i;     }      // Sort the vector V     Arrays.sort(V, (a, b) -> a[0] - b[0]);      // Stores the total number of     // operations required     int cnt = 0;     int f = 1;      // Iterate until f equals 1     while (f == 1) {        // Update f equals zero       f = 0;        // Traverse through vector       // and check for i and i+1       for (int i = 0; i < n - 1; i++) {          // If current position of         // i is at least current         // position of i+1         if (V[i][2] >= V[i + 1][2]) {            // Increase the current           // position of V[i+1][2]           // by V[i+1][1]           V[i + 1][2] += V[i + 1][1];            // Increment the count           // of operations           cnt++;            // Update the flag equals           // to 1           f = 1;            // Break the for loop           break;         }       }     }      // Return the total operations     // required     return cnt;   }    // Driver Code   public static void main(String[] args)   {     int A[] = { 2, 1, 4, 3 };     int B[] = { 4, 1, 2, 4 };     int N = A.length;      System.out.println(minHits(A, B, N));   }  }  // This code is contributed by Pushpesh Raj. 
Python3
# python 3 program for the above approach  # Function to find minimum number of # operations required to sort N array # elements placed on a number line def minHits(arr, move, n):     # Stores the value of     # {A[i], B[i], current position}     temp = [0 for i in range(3)]     V = [temp for i in range(n)]       # Populate the current position     # every elements     for i in range(n):         V[i] = [arr[i], move[i], i]      # Sort the vector V     V.sort()      # Stores the total number of     # operations required     cnt = 0     f = 1      # Iterate until f equals 1     while(f == 1):         # Update f equals zero         f = 0          # Traverse through vector         # and check for i and i+1         for i in range(n - 1):             # If current position of             # i is at least current             # position of i+1             if (V[i][2] >= V[i + 1][2]):                 # Increase the current                 # position of V[i+1][2]                 # by V[i+1][1]                 V[i + 1][2] += V[i + 1][1]                  # Increment the count                 # of operations                 cnt += 1                  # Update the flag equals                 # to 1                 f = 1                  # Break the for loop                 break      # Return the total operations     # required     return cnt  # Driver Code if __name__ == '__main__':     A = [2, 1, 4, 3]     B = [4, 1, 2, 4]     N = len(A)     print(minHits(A, B, N))          # This code is contributed by bgangwar59. 
C#
// C# program for the above approach using System; using System.Linq;  class GFG {      // Function to find minimum number of   // operations required to sort N array   // elements placed on a number line   public static int minHits(int[] arr, int[] move, int n)   {          // Stores the value of     // {A[i], B[i], current position}     int[][] V = new int[n][];      // Populate the current position     // every elements     for (int i = 0; i < n; i++)     {       V[i] = new int[] { arr[i], move[i], i };     }      // Sort the vector V     Array.Sort(V, (a, b) => a[0] - b[0]);      // Stores the total number of     // operations required     int cnt = 0;     int f = 1;      // Iterate until f equals 1     while (f == 1)     {       // Update f equals zero       f = 0;        // Traverse through vector       // and check for i and i+1       for (int i = 0; i < n - 1; i++)       {         // If current position of         // i is at least current         // position of i+1         if (V[i][2] >= V[i + 1][2])         {           // Increase the current           // position of V[i+1][2]           // by V[i+1][1]           V[i + 1][2] += V[i + 1][1];            // Increment the count           // of operations           cnt++;            // Update the flag equals           // to 1           f = 1;            // Break the for loop           break;         }       }     }      // Return the total operations     // required     return cnt;   }    // Driver Code   public static void Main(string[] args)   {     int[] A = new int[] { 2, 1, 4, 3 };     int[] B = new int[] { 4, 1, 2, 4 };     int N = A.Length;      Console.WriteLine(minHits(A, B, N));   } }  // This code is contributed by Aman Kumar. 
JavaScript
<script>  // JavaScript program for the above approach  // Function to find minimum number of // operations required to sort N array // elements placed on a number line function minHits(arr, move, n) {     // Stores the value of     // {A[i], B[i], current position}     let V = new Array(n).fill(0).map(() => new Array(3));      // Populate the current position     // every elements     for (let i = 0; i < n; i++) {         V[i] = [arr[i], move[i], i];     }      // Sort the vector V     V.sort((a, b) => a[0] - b[0]);      // Stores the total number of     // operations required     let cnt = 0;     let f = 1;      // Iterate until f equals 1     while (f == 1) {          // Update f equals zero         f = 0;          // Traverse through vector         // and check for i and i+1         for (let i = 0; i < n - 1; i++) {              // If current position of             // i is at least current             // position of i+1             if (V[i][2] >= V[i + 1][2]) {                  // Increase the current                 // position of V[i+1][2]                 // by V[i+1][1]                 V[i + 1][2] += V[i + 1][1];                  // Increment the count                 // of operations                 cnt++;                  // Update the flag equals                 // to 1                 f = 1;                  // Break the for loop                 break;             }         }     }      // Return the total operations     // required     return cnt; }  // Driver Code  let A = [2, 1, 4, 3]; let B = [4, 1, 2, 4]; let N = A.length;  document.write(minHits(A, B, N));  </script> 

Output: 
5

 

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


Next Article
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same
author
vedant_1
Improve
Article Tags :
  • Sorting
  • Mathematical
  • Competitive Programming
  • C++ Programs
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Mathematical
  • Sorting

Similar Reads

  • Convert A into B by incrementing or decrementing 1, 2, or 5 any number of times
    Given two integers A and B, the task is to find the minimum number of moves needed to make A equal to B by incrementing or decrementing the A by either 1, 2, or 5 any number of times. Examples: Input: A = 4, B = 0Output: 2Explanation:Perform the operation as follows: Decreasing the value of A by 2,
    4 min read
  • Minimum number of swaps required to sort an array | Set 2
    Given an array of N distinct elements, find the minimum number of swaps required to sort the array. Note: The problem is not asking to sort the array by the minimum number of swaps. The problem is to find the minimum swaps in which the array can be sorted. Examples: Input: arr[] = {4, 3, 2, 1} Outpu
    7 min read
  • Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same
    Given two arrays A[] and B[] consisting of N integers (N is odd), the task is to rearrange array B[] such that for each 1 ? i ? N, Bitwise XOR of A[i] and B[i] is the same. If no such rearrangement is possible, print "-1". Otherwise, print the rearrangement. Examples: Input: A[] = {1, 2, 3, 4, 5}, B
    9 min read
  • Sort array such that absolute difference of adjacent elements is in increasing order
    Given an unsorted array of length N. The task is to sort the array, such that abs(a[i]-a[i+1]) < = abs(a[i+1]-a[i+2]) for all 0 < = i< N that is abs(a[0]-a[1]) < = abs(a[1]-a[2]) < = abs(a[2]-a[3]) and so on.Examples: Input: arr[] = {7, 4, 9, 9, -1, 9}Output: {9, 7, 9, 4, 9, -1}Explan
    7 min read
  • Minimize insertions and deletions in given array A[] to make it identical to array B[]
    Given two arrays A[] and B[] of length N and M respectively, the task is to find the minimum number of insertions and deletions on the array A[], required to make both the arrays identical.Note: Array B[] is sorted and all its elements are distinct, operations can be performed at any index not neces
    15+ min read
  • C++ Program to Check if it is possible to sort the array after rotating it
    Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of t
    3 min read
  • C++ Program for Sorting array except elements in a subarray
    Given an array A positive integers, sort the array in ascending order such that element in given subarray (start and end indexes are input) in unsorted array stay unmoved and all other elements are sorted.Examples : Input : arr[] = {10, 4, 11, 7, 6, 20} l = 1, u = 3 Output : arr[] = {6, 4, 11, 7, 10
    2 min read
  • Partitioning into two contiguous element subarrays with equal sums
    Given an array of n positive integers. Find a minimum positive element to be added to one of the indexes in the array such that it can be partitioned into two contiguous sub-arrays of equal sums. Output the minimum element to be added and the position where it is to be added. If multiple positions a
    10 min read
  • Count minimum moves required to convert A to B
    Given two integers A and B, convert A to B by performing one of the following operations any number of times: A = A + KA = A - K, where K belongs to [1, 10] The task is to find the minimum number of operations required to convert A to B using the above operations. Examples: Input: A = 13, B = 42Outp
    4 min read
  • C++ Program For Selection Sort
    The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. The subarray which is already sorted. Remaining subarray which is unsorted.
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences