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:
Minimum no. of operations required to make all Array Elements Zero
Next article icon

Minimum operations of given type required to empty given array

Last Updated : 29 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N, the task is to find the total count of operations required to remove all the array elements such that if the first element of the array is the smallest element, then remove that element, otherwise move the first element to the end of the array.

Examples:

Input: A[] = {8, 5, 2, 3}
Output: 7
Explanation: Initially, A[] = {8, 5, 2, 3}
Step 1: 8 is not the smallest. Therefore, moving it to the end of the array modifies A[] to {5, 2, 3, 8}.
Step 2: 5 is not the smallest. Therefore, moving it to the end of the array modifies A[] to {2, 3, 8, 5}.
Step 3: 2 is the smallest. Therefore, removing it from the array modifies A[] to {3, 8, 5}
Step 4: 3 is the smallest. Therefore, removing it from the array modifies A[] to A[] = {5, 8}
Step 6: 5 is smallest. Therefore, removing it from the array modifies A[] to {8}
Step 7: 8 is the smallest. Therefore, removing it from the array modifies A[] to {}
Therefore, 7 operations are required to delete the whole array.

Input: A[] = {8, 6, 5, 2, 7, 3, 10}
Output: 18

Naive Approach: The simplest approach to solve the problem is to repeatedly check if the first array element is the smallest element of the array or not. If found to be true, then remove that element and increment the count. Otherwise, move the first element of the array to the end of the array and increment the count. Finally, print the total count obtained.
Time Complexity: O(N3)
Auxiliary Space: O(N)

Efficient Approach: The problem can be efficiently solved using a dynamic programming approach and a sorting algorithm. Follow the steps below to solve the problem:

  1. Store the elements of array A[] with their indices into a vector of pairs, say vector a.
  2. Sort the vector according to the values of the elements.
  3. Initialize arrays countGreater_right[] and countGreater_left[] to store the number of greater elements present in the right of the current element and the number of greater elements present in the left of the current element in the given array respectively which can be done using a set data structure.
  4. Initially, store the index of starting element of vector a as prev = a[0].second.
  5. Initialize count with prev+1.
  6. Now, traverse each element of vector a, from i = 1 to N-1.
  7. For each element, retrieve its original index as ind = a[i].second and the dp transition for each element is:

If ind > prev, increment count by countGreater_right[prev] - countGreater_right[ind], otherwise

Increment count by countGreater_right[prev] + countGreater_left[ind] + 1.

        8. After traversing, print count as the answer.

Below is the implementation of the above algorithm:

C++
#include <bits/stdc++.h> using namespace std;  // Function to find the count of greater elements // to right of each index vector<int> countGreaterRight(vector<int>& A, int lenn,                                vector<int>& countGreater_right) {     // Store elements of array in sorted order     map<int, int> s;     // Traverse the array in reverse order     for (int i = lenn - 1; i >= 0; i--) {         int it = distance(s.begin(), s.lower_bound(A[i]));         // Stores count of greater elements on the right of i         countGreater_right[i] = it;         // Insert current element         s[A[i]] = 1;     }     return countGreater_right; }  // Function to find the count of greater elements // to left of each index vector<int> countGreaterLeft(vector<int>& A, int lenn, vector<int>& countGreater_left) {     // Store elements of array in sorted order     map<int, int> s;     // Traverse the array in forward order     for (int i = 0; i < lenn; i++) {         int it = distance(s.begin(), s.lower_bound(A[i]));         // Stores count of greater elements on the left of i         countGreater_left[i] = it;         // Insert current element         s[A[i]] = 1;     }     return countGreater_left; }  // Function to find the count of operations required // to remove all the array elements such that If // 1st elements is smallest then remove the element // otherwise move the element to the end of array void cntOfOperations(int N, vector<int>& A) {     // Store {A[i], i}     vector<vector<int>> a(N, vector<int>(2));     // Traverse the array     for (int i = 0; i < N; i++) {         // Insert {A[i], i}         a[i][0] = A[i];         a[i][1] = i;     }     // Sort the array according to elements of the array, A[]     sort(a.begin(), a.end());     // countGreater_right[i]: Stores count of greater elements on the right side of i     vector<int> countGreater_right(N);     // countGreater_left[i]: Stores count of greater elements on the left side of i     vector<int> countGreater_left(N);     // Function to fill the arrays     countGreater_right = countGreaterRight(A, N, countGreater_right);     countGreater_left = countGreaterLeft(A, N, countGreater_left);     // Index of smallest element in array A[]     int prev = a[0][1], ind = 0;     // Stores count of greater element on left side of index i     int count = prev;     // Iterate over remaining elements in of a[][]     for (int i = 1; i < N; i++) {         // Index of next smaller element         ind = a[i][1];         // If ind is greater         if (ind > prev) {             // Update count             count += countGreater_right[prev] - countGreater_right[ind];         } else {             // Update count             count += countGreater_right[prev] + countGreater_left[ind] + 1;         }         // Update prev         prev = ind;     }     // Print count as total number of operations     cout << count+1 << endl; }  // Driver Code int main() {     // Given array     vector<int> A = { 8, 5, 2, 3 };         // Given size         int N = A.size();      // Function Call     cntOfOperations(N, A); } 
Java
import java.util.*; import java.io.*;  public class Main {    // Function to find the count of greater elements   // to right of each index   public static int[] countGreaterRight(int[] A, int lenn,                                         int[] countGreater_right)    {          // Store elements of array in sorted order     TreeMap<Integer, Integer> s = new TreeMap<Integer, Integer>();      // Traverse the array in reverse order     for (int i = lenn - 1; i >= 0; i--) {       int it = s.headMap(A[i]).size();        // Stores count of greater elements on the right of i       countGreater_right[i] = it;        // Insert current element       s.put(A[i], 1);     }     return countGreater_right;   }    // Function to find the count of greater elements   // to left of each index   public static int[] countGreaterLeft(int[] A, int lenn, int[] countGreater_left) {     // Store elements of array in sorted order     TreeMap<Integer, Integer> s = new TreeMap<Integer, Integer>();      // Traverse the array in forward order     for (int i = 0; i < lenn; i++) {       int it = s.headMap(A[i]).size();        // Stores count of greater elements on the left of i       countGreater_left[i] = it;        // Insert current element       s.put(A[i], 1);     }     return countGreater_left;   }    // Function to find the count of operations required   // to remove all the array elements such that If   // 1st elements is smallest then remove the element   // otherwise move the element to the end of array   public static void cntOfOperations(int N, int[] A) {     // Store {A[i], i}     int[][] a = new int[N][2];      // Traverse the array     for (int i = 0; i < N; i++) {       // Insert {A[i], i}       a[i][0] = A[i];       a[i][1] = i;     }      // Sort the array according to elements of the array, A[]     Arrays.sort(a, Comparator.comparingInt(o -> o[0]));      // countGreater_right[i]: Stores count of greater elements on the right side of i     int[] countGreater_right = new int[N];      // countGreater_left[i]: Stores count of greater elements on the left side of i     int[] countGreater_left = new int[N];      // Function to fill the arrays     countGreater_right = countGreaterRight(A, N, countGreater_right);     countGreater_left = countGreaterLeft(A, N, countGreater_left);      // Index of smallest element in array A[]     int prev = a[0][1], ind = 0;      // Stores count of greater element on left side of index i     int count = prev;      // Iterate over remaining elements in of a[][]     for (int i = 1; i < N; i++) {       // Index of next smaller element       ind = a[i][1];        // If ind is greater       if (ind > prev) {         // Update count         count += countGreater_right[prev] - countGreater_right[ind];       } else {         // Update count         count += countGreater_right[prev] + countGreater_left[ind] + 1;       }        // Update prev       prev = ind;     }      // Print count as total number of operations     System.out.println(count+1);   }    // Driver Code   public static void main(String[] args)   {          // Given array     int[] A = {8, 5, 2, 3};      // Given size     int N = A.length;      // Function Call     cntOfOperations(N, A);   } } 
Python3
# Python3 program for the above approach from bisect import bisect_left, bisect_right  # Function to find the count of greater # elements to right of each index def countGreaterRight(A, lenn,countGreater_right):      # Store elements of array     # in sorted order     s = {}      # Traverse the array in reverse order     for i in range(lenn-1, -1, -1):         it = bisect_left(list(s.keys()), A[i])          # Stores count of greater elements         # on the right of i         countGreater_right[i] = it          # Insert current element         s[A[i]] = 1     return countGreater_right  # Function to find the count of greater # elements to left of each index def countGreaterLeft(A, lenn,countGreater_left):      # Store elements of array     # in sorted order     s = {}      # Traverse the array in reverse order     for i in range(lenn):         it = bisect_left(list(s.keys()), A[i])          # Stores count of greater elements         # on the right of i         countGreater_left[i] = it          # Insert current element         s[A[i]] = 1     return countGreater_left  # Function to find the count of operations required # to remove all the array elements such that If # 1st elements is smallest then remove the element # otherwise move the element to the end of array def cntOfOperations(N, A):      # Store {A[i], i}     a = []      # Traverse the array     for i in range(N):          # Insert {A[i], i}         a.append([A[i], i])      # Sort the vector pair according to     # elements of the array, A[]     a = sorted(a)      # countGreater_right[i]: Stores count of     # greater elements on the right side of i     countGreater_right = [0 for i in range(N)]      # countGreater_left[i]: Stores count of     # greater elements on the left side of i     countGreater_left = [0 for i in range(N)]      # Function to fill the arrays     countGreater_right = countGreaterRight(A, N,                                             countGreater_right)     countGreater_left = countGreaterLeft(A, N,                                           countGreater_left)      # Index of smallest element     # in array A[]     prev, ind = a[0][1], 0      # Stores count of greater element     # on left side of index i     count = prev      # Iterate over remaining elements     # in of a[][]     for i in range(N):          # Index of next smaller element         ind = a[i][1]          # If ind is greater         if (ind > prev):              # Update count             count += countGreater_right[prev] - countGreater_right[ind]          else:             # Update count             count += countGreater_right[prev] + countGreater_left[ind] + 1          # Update prev         prev = ind      # Print count as total number     # of operations     print (count)  # Driver Code if __name__ == '__main__':      # Given array     A = [8, 5, 2, 3 ]      # Given size     N = len(A)      # Function Call     cntOfOperations(N, A)  # This code is contributed by mohit kumar 29 
C#
// C# code addition  using System; using System.Collections.Generic; using System.Linq; using System.Collections; public class Program {     // Function to find the count of greater elements     // to right of each index     public static int[] CountGreaterRight(int[] A, int lenn,                                         int[] countGreater_right)     {          // Store elements of array in sorted order         SortedDictionary<int, int> s = new SortedDictionary<int, int>();          // Traverse the array in reverse order         for (int i = lenn - 1; i >= 0; i--)         {             int it = s.TakeWhile(x => x.Key < A[i]).Count();              // Stores count of greater elements on the right of i             countGreater_right[i] = it;              // Insert current element             s[A[i]] = 1;         }         return countGreater_right;     }      // Function to find the count of greater elements     // to left of each index     public static int[] CountGreaterLeft(int[] A, int lenn, int[] countGreater_left)     {         // Store elements of array in sorted order         SortedDictionary<int, int> s = new SortedDictionary<int, int>();          // Traverse the array in forward order         for (int i = 0; i < lenn; i++)         {             int it = s.TakeWhile(x => x.Key < A[i]).Count();              // Stores count of greater elements on the left of i             countGreater_left[i] = it;              // Insert current element             s[A[i]] = 1;         }         return countGreater_left;     }      // Function to find the count of operations required     // to remove all the array elements such that If     // 1st elements is smallest then remove the element     // otherwise move the element to the end of array     public static void CntOfOperations(int N, int[] A)     {         // Store {A[i], i}         int[][] a = new int[N][];          // Traverse the array         for (int i = 0; i < N; i++)         {             // Insert {A[i], i}             a[i] = new int[2] { A[i], i };         }          // Sort the array according to elements of the array, A[]         Array.Sort(a, (x, y) => x[0].CompareTo(y[0]));          // countGreater_right[i]: Stores count of greater elements on the right side of i         int[] countGreater_right = new int[N];          // countGreater_left[i]: Stores count of greater elements on the left side of i         int[] countGreater_left = new int[N];          // Function to fill the arrays         countGreater_right = CountGreaterRight(A, N, countGreater_right);         countGreater_left = CountGreaterLeft(A, N, countGreater_left);          // Index of smallest element in array A[]         int prev = a[0][1], ind = 0;          // Stores count of greater element on left side of index i         int count = prev;          // Iterate over remaining elements in of a[][]         for (int i = 1; i < N; i++)         {             // Index of next smaller element             ind = a[i][1];              // If ind is greater             if (ind > prev)             {                 // Update count                 count += countGreater_right[prev] - countGreater_right[ind];             }             else             {                 // Update count                 count += countGreater_right[prev] + countGreater_left[ind] + 1;               }        // Update prev       prev = ind;     }      // Print count as total number of operations     Console.WriteLine(count+1);   }    // Driver Code   static void Main()   {          // Given array     int[] A = {8, 5, 2, 3};      // Given size     int N = A.Length;      // Function Call     CntOfOperations(N, A);   } }  // The code is contributed by Nidhi goel.  
JavaScript
function countGreaterRight(A, lenn, countGreater_right) { // Store elements of array in sorted order let s = new Map();  // Traverse the array in reverse order for (let i = lenn - 1; i >= 0; i--) { let it = [...s.keys()].filter((x) => x < A[i]).length; // Stores count of greater elements on the right of i countGreater_right[i] = it;  // Insert current element s.set(A[i], 1); } return countGreater_right; }  function countGreaterLeft(A, lenn, countGreater_left) { // Store elements of array in sorted order let s = new Map();  // Traverse the array in forward order for (let i = 0; i < lenn; i++) { let it = [...s.keys()].filter((x) => x < A[i]).length; // Stores count of greater elements on the left of i countGreater_left[i] = it;  // Insert current element s.set(A[i], 1); } return countGreater_left; }  function cntOfOperations(N, A) { // Store {A[i], i} let a = [];  // Traverse the array for (let i = 0; i < N; i++) { // Insert {A[i], i} a.push([A[i], i]); } // Sort the array according to elements of the array, A[] a.sort((x, y) => x[0] - y[0]);  // countGreater_right[i]: Stores count of greater elements on the right side of i let countGreater_right = new Array(N).fill(0);  // countGreater_left[i]: Stores count of greater elements on the left side of i let countGreater_left = new Array(N).fill(0);  // Function to fill the arrays countGreater_right = countGreaterRight(A, N, countGreater_right); countGreater_left = countGreaterLeft(A, N, countGreater_left);  // Index of smallest element in array A[] let prev = a[0][1], ind = 0;  // Stores count of greater element on left side of index i let count = prev;  // Iterate over remaining elements in of a[][] for (let i = 1; i < N; i++) { // Index of next smaller element ind = a[i][1]; // If ind is greater if (ind > prev) {   // Update count   count += countGreater_right[prev] - countGreater_right[ind]; } else {   // Update count   count += countGreater_right[prev] + countGreater_left[ind] + 1; }  // Update prev prev = ind; }  // Print count as total number of operations console.log(count + 1); }  // Driver Code let A = [8, 5, 2, 3];  // Given size let N = A.length;  // Function Call cntOfOperations(N, A); 

Output: 
7

 

Time Complexity:O(N2)
Auxiliary Space: O(N)

Note: The above approach can be optimized by finding the count of greater elements on the left and right side of each index using Fenwick Tree.


Next Article
Minimum no. of operations required to make all Array Elements Zero

M

ManikantaBandla
Improve
Article Tags :
  • Searching
  • Sorting
  • Mathematical
  • DSA
  • Arrays
  • array-rearrange
Practice Tags :
  • Arrays
  • Mathematical
  • Searching
  • Sorting

Similar Reads

  • Minimum no. of operations required to make all Array Elements Zero
    Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.
    12 min read
  • Minimum number of steps required to obtain the given Array by the given operations
    Given an array arr[] of N positive integers, the task is to find the minimum number of operations required of the following types to obtain the array arr[] from an array of zeroes only. Select any index i and increment all the elements at the indices [i, N - 1] by 1.Select any index i and decrease a
    12 min read
  • Minimum number of given operations required to reduce the array to 0 element
    Given an array arr[] of N integers. The task is to find the minimum number of given operations required to reduce the array to 0 elements. In a single operation, any element can be chosen from the array and all of its multiples get removed including itself.Examples: Input: arr[] = {2, 4, 6, 3, 4, 6,
    6 min read
  • Minimum operations required to make two elements equal in Array
    Given array A[] of size N and integer X, the task is to find the minimum number of operations to make any two elements equal in the array. In one operation choose any element A[i] and replace it with A[i] & X. where & is bitwise AND. If such operations do not exist print -1. Examples: Input:
    9 min read
  • Minimum length of the reduced Array formed using given operations
    Given an array arr of length N, the task is to minimize its length by performing following operations: Remove any adjacent equal pairs, ( i.e. if arr[i] = arr[i+1]) and replace it with single instance of arr[i] + 1.Each operation decrements the length of the array by 1.Repeat the operation till no m
    10 min read
  • Minimum increment/decrement operations required on Array to satisfy given conditions
    Given an array arr[] of size N, the task is to find the minimum number of increment or decrement operations required at any index i such that for each i (1 ? i < N) if the sum of elements at index from 1 to i is positive then the sum of elements from 1 to i + 1 must be negative or vice versa. Not
    11 min read
  • Minimum operations required to sort the array
    Given an array arr[], the task is to find the minimum operations required to sort the array in increasing order. In one operation, you can set each occurrence of one element to 0. Examples: Input: item[] = [4, 1, 5, 3, 2]Output: 4Explanation: Set arr[0], arr[1], arr[2], arr[3] = 0. Hence, the minimu
    7 min read
  • Minimum operations required to make all the array elements equal
    Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets d
    6 min read
  • Minimum operations required to make all elements of Array less than equal to 0
    Given an array arr[] consisting of N positive numbers, the task is to find the minimum number of operations required to make all elements of the array less than or equal to 0. In each operation, one has to pick the minimum positive element from the array and subtract all the elements of the array fr
    5 min read
  • Minimum number of operations required to delete all elements of the array
    Given an integer array arr, the task is to print the minimum number of operations required to delete all elements of the array. In an operation, any element from the array can be chosen at random and every element divisible by it can be removed from the array. Examples: Input: arr[] = {2, 4, 6, 3, 5
    9 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