Skip to content
Related Articles

Related Articles

Minimum operations of given type required to empty given array
  • Last Updated : 06 Jan, 2021

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 modifes A[] to {5, 2, 3, 8}.
Step 2: 5 is not the smallest. Therefore, moving it to the end of the array modifes A[] to {2, 3, 8, 5}.
Step 3: 2 is the smallest. Therefore, removing it from the array modifes A[] to {3, 8, 5}
Step 4: 3 is the smallest. Therefore, removing it from the array modifes A[] to A[] = {5, 8}
Step 6: 5 is smallest. Therefore, removing it from the array modifes A[] to {8}
Step 7: 8 is the smallest. Therefore, removing it from the array modifes 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include
#include
using namespace std;
 
// Function to find the count of greater
// elements to right of each index
void countGreaterRight(int A[], int len,
                       int* countGreater_right)
{
 
    // Store elements of array
    // in sorted order
    multiset s;
 
    // Traverse the array in reverse order
    for (int i = len - 1; i >= 0; i--) {
        auto it = s.lower_bound(A[i]);
 
        // Stores count of greater elements
        // on the right of i
        countGreater_right[i]
            = distance(it, s.end());
 
        // Insert current element
        s.insert(A[i]);
    }
}
 
// Function to find the count of greater
// elements to left of each index
void countGreaterLeft(int A[], int len,
                      int* countGreater_left)
{
 
    // Stores elements in
    // a sorted order
    multiset s;
 
    // Traverse the array
    for (int i = 0; i <= len; i++) {
        auto it = s.lower_bound(A[i]);
 
        // Stores count of greater elements
        // on the left side of i
        countGreater_left[i]
            = distance(it, s.end());
 
        // Insert current element into multiset
        s.insert(A[i]);
    }
}
 
// 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, int A[])
{
    int i;
 
    // Store {A[i], i}
    vector<pair > a;
 
    // Traverse the array
    for (i = 0; i < N; i++) {
 
        // Insert {A[i], i}
        a.push_back(make_pair(A[i], i));
    }
 
    // Sort the vector pair 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
    int countGreater_right[N];
 
    // countGreater_left[i]: Stores count of
    // greater elements on the left side of i
    int countGreater_left[N];
 
    // Function to fill the arrays
    countGreaterRight(A, N, countGreater_right);
    countGreaterLeft(A, N, countGreater_left);
 
    // Index of smallest element
    // in array A[]
    int prev = a[0].second, ind;
 
    // Stores count of greater element
    // on left side of index i
    int count = prev + 1;
 
    // Iterate over remaining elements
    // in of a[][]
    for (i = 1; i  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;
}
 
// Driver Code
int main()
{
 
    // Given array
    int A[] = { 8, 5, 2, 3 };
 
    // Given size
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cntOfOperations(N, A);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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
 
    # Prcount 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

chevron_right


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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :