VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-operations-required-to-vanish-all-elements/

⇱ Minimum number of operations required to vanish all elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of operations required to vanish all elements

Last Updated : 23 Jul, 2025

Given an array A[] length N along with an integer K. Select a subarray of size K and replace all elements with X (Cross), which has a minimum value in that subarray. Then the task is to output the minimum number of operations required to convert all the elements into X.

Note:

  • If there are elements which are already replaced with X, then leave them and apply operation on rest of the elements.
  • If there are multiple elements with same minimum value, then replace all of them with X.

Examples:

Input: N = 5, K = 3, A[] = {50, 40, 50, 40, 50}
Output: 3
Explanation:

  • First operation: Choose subarray A[2, 4], which has a length equal to 3. So, A[2, 4] = {40, 50, 40}. The minimum value is 40. Therefore, replace all 40 with X in this subarray. Then, A[2, 4] = {X, 50, X}. Now, A[] = {50, X, 50, X, 50}
  • Second operation: Choose subarray A[1, 3], which has a length equal to 3. So, A[1, 3] = {50, X, 50}. The minimum value is 50. Therefore, replace all 50 with X in this subarray. Then, A[1, 3] = {X, X, X}. Now, A[] = {X, X, X, X, 50}
  • Third operation: Choose subarray A[3, 5], which has a length equal to 3. So, A[3, 5] = {X, X, 50}. The minimum value is 50. Therefore, replace 50 with X in this subarray. Then, A[1, 3] = {X, X, X}. Now, A[] = {X, X, X, X, X}

Now, it can be verified that all the elements are replaced with X (Cross). Therefore, minimum number of operations are required is 3.

Input: N = 3, K = 2, A[] = {10, 20, 20}
Output: 2
Explanation: It can be verified that minimum number of operations required will be 2.

Approach: Implement the idea below to solve the problem

The problem is based on Greedy logic and can be solved by using some observations. For solving this problem, we have to use ArrayList and HashMap. ArrayList will be used to store distinct elements and HashMap will store the indices of elements, which appears more than once.

Steps were taken to solve the problem:

  • Create an ArrayList let say List to store distinct elements.
  • Create a HashMap of <Integer, ArrayList<Integer>> type let say Map to store the list of indices of a element.
  • sort the List so that minimum elements removed first.
  • For each element traverse the indices and calculate the number of operations to remove all the occurrences of element.
  • Output the value of minimum number of operations.

Code to implement the approach:


Output
2

Time Complexity: O(N)
Auxiliary Space: O(N), As HashMap and ArrayList are used.

Comment