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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Minimum number of elements to be removed such that the sum of the remaining elements is equal to k
Next article icon

Minimize count of array elements to be removed such that at least K elements are equal to their index values

Last Updated : 02 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[](1- based indexing) consisting of N integers and a positive integer K, the task is to find the minimum number of array elements that must be removed such that at least K array elements are equal to their index values. If it is not possible to do so, then print -1.

Examples:

Input: arr[] = {5, 1, 3, 2, 3}  K = 2
Output: 2 
Explanation:
Following are the removal operations required:

  • Removing arr[1] modifies array to {1, 3, 2, 3} -> 1 element is equal to its index value.
  • Removing arr[3] modifies array to {1, 2, 3} -> 3 elements are equal to their index value.

After the above operations 3(>= K) elements are equal to their index values and the minimum removals required is 2.

Input: arr[] = {2, 3, 4}  K = 1
Output: -1 

Approach: The above problem can be solved with the help of Dynamic Programming. Follow the steps below to solve the given problem.

  • Initialize a 2-D dp table such that dp[i][j] will denote maximum elements that have values equal to their indexes when a total of j elements are present.
  • All the values in the dp table are initially filled with 0s.
  • Iterate for each i in the range [0, N-1] and j in the range [0, i], there are two choices.
    • Delete the current element, the dp table can be updated as dp[i+1][j] = max(dp[i+1][j], dp[i][j]).
    • Keep the current element, then dp table can be updated as: dp[i+1][j+1] = max(dp[i+1][j+1], dp[i][j] + (arr[i+1] == j+1)).
  • Now for each j in the range [N, 0] check if the value of dp[N][j] is greater than or equal to K. Take minimum if found and return the answer.
  • Otherwise, return -1 at the end. That means no possible answer is found.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to minimize the removals of // array elements such that atleast K // elements are equal to their indices int MinimumRemovals(int a[], int N, int K) {     // Store the array as 1-based indexing     // Copy of first array     int b[N + 1];     for (int i = 0; i < N; i++) {         b[i + 1] = a[i];     }      // Make a dp-table of (N*N) size     int dp[N + 1][N + 1];      // Fill the dp-table with zeroes     memset(dp, 0, sizeof(dp));     for (int i = 0; i < N; i++) {         for (int j = 0; j <= i; j++) {              // Delete the current element             dp[i + 1][j] = max(                 dp[i + 1][j], dp[i][j]);              // Take the current element             dp[i + 1][j + 1] = max(                 dp[i + 1][j + 1],                 dp[i][j] + ((b[i + 1] == j + 1) ? 1 : 0));         }     }      // Check for the minimum removals     for (int j = N; j >= 0; j--) {         if (dp[N][j] >= K) {             return (N - j);         }     }     return -1; }  // Driver Code int main() {     int arr[] = { 5, 1, 3, 2, 3 };     int K = 2;     int N = sizeof(arr) / sizeof(arr[0]);     cout << MinimumRemovals(arr, N, K);      return 0; } 
Java
// Java program for the above approach  import java.io.*;  class GFG {      // Function to minimize the removals of     // array elements such that atleast K     // elements are equal to their indices     static int MinimumRemovals(int a[], int N, int K)     {         // Store the array as 1-based indexing         // Copy of first array         int b[] = new int[N + 1];         for (int i = 0; i < N; i++) {             b[i + 1] = a[i];         }          // Make a dp-table of (N*N) size         int dp[][] = new int[N + 1][N + 1];          for (int i = 0; i < N; i++) {             for (int j = 0; j <= i; j++) {                  // Delete the current element                 dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][j]);                  // Take the current element                 dp[i + 1][j + 1] = Math.max(                     dp[i + 1][j + 1],                     dp[i][j]                         + ((b[i + 1] == j + 1) ? 1 : 0));             }         }          // Check for the minimum removals         for (int j = N; j >= 0; j--) {             if (dp[N][j] >= K) {                 return (N - j);             }         }         return -1;     }      // Driver Code     public static void main(String[] args)     {         int arr[] = { 5, 1, 3, 2, 3 };         int K = 2;         int N = arr.length;         System.out.println(MinimumRemovals(arr, N, K));     } }  // This code is contributed by Dharanendra L V. 
Python3
# Python 3 program for the above approach  # Function to minimize the removals of # array elements such that atleast K # elements are equal to their indices def MinimumRemovals(a, N, K):        # Store the array as 1-based indexing     # Copy of first array     b = [0 for i in range(N + 1)]     for i in range(N):         b[i + 1] = a[i]      # Make a dp-table of (N*N) size     dp = [[0 for i in range(N+1)] for j in range(N+1)]      for i in range(N):         for j in range(i + 1):                        # Delete the current element             dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])              # Take the current element             dp[i + 1][j + 1] = max(dp[i + 1][j + 1],dp[i][j] + (1 if (b[i + 1] == j + 1) else 0))      # Check for the minimum removals     j = N     while(j >= 0):         if(dp[N][j] >= K):             return (N - j)         j -= 1     return -1  # Driver Code if __name__ == '__main__':     arr = [5, 1, 3, 2, 3]     K = 2     N = len(arr)     print(MinimumRemovals(arr, N, K))          # This code is contributed by SURENDRA_GANGWAR. 
C#
// C# code for the above approach using System;  public class GFG {        // Function to minimize the removals of     // array elements such that atleast K     // elements are equal to their indices     static int MinimumRemovals(int[] a, int N, int K)     {                // Store the array as 1-based indexing         // Copy of first array         int[] b = new int[N + 1];         for (int i = 0; i < N; i++) {             b[i + 1] = a[i];         }          // Make a dp-table of (N*N) size         int[, ] dp = new int[N + 1, N + 1];          for (int i = 0; i < N; i++) {             for (int j = 0; j <= i; j++) {                  // Delete the current element                 dp[i + 1, j]                     = Math.Max(dp[i + 1, j], dp[i, j]);                  // Take the current element                 dp[i + 1, j + 1] = Math.Max(                     dp[i + 1, j + 1],                     dp[i, j]                         + ((b[i + 1] == j + 1) ? 1 : 0));             }         }          // Check for the minimum removals         for (int j = N; j >= 0; j--) {             if (dp[N, j] >= K) {                 return (N - j);             }         }         return -1;     }      static public void Main()     {          // Code         int[] arr = { 5, 1, 3, 2, 3 };         int K = 2;         int N = arr.Length;         Console.Write(MinimumRemovals(arr, N, K));     } }  // This code is contributed by Potta Lokesh 
JavaScript
<script> // Javascript program for the above approach  // Function to minimize the removals of // array elements such that atleast K // elements are equal to their indices function MinimumRemovals(a, N, K) {      // Store the array as 1-based indexing     // Copy of first array     let b = new Array(N + 1);     for (let i = 0; i < N; i++) {         b[i + 1] = a[i];     }      // Make a dp-table of (N*N) size     let dp = new Array(N + 1).fill(0).map(() => new Array(N + 1).fill(0));      for (let i = 0; i < N; i++) {         for (let j = 0; j <= i; j++) {              // Delete the current element             dp[i + 1][j] = Math.max(                 dp[i + 1][j], dp[i][j]);              // Take the current element             dp[i + 1][j + 1] = Math.max(                 dp[i + 1][j + 1],                 dp[i][j] + ((b[i + 1] == j + 1) ? 1 : 0));         }     }      // Check for the minimum removals     for (let j = N; j >= 0; j--) {         if (dp[N][j] >= K) {             return (N - j);         }     }     return -1; }  // Driver Code      let arr = [ 5, 1, 3, 2, 3 ];     let K = 2;     let N = arr.length     document.write(MinimumRemovals(arr, N, K));          // This code is contributed by _saurabh_jaiswal. </script> 

 
 


Output
2


 

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


Efficient approach : Space optimization

In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.

Implementation steps:

  • Create a 1D vector dp of size N+1 and initialize it with 0.
  • Set a base case by initializing the values of DP .
  • Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
  • At last iterate over Dp and whenever dp[j] >= K  return (N - j) .

Implementation: 

C++
#include <bits/stdc++.h> using namespace std;  // Function to minimize the removals of // array elements such that atleast K // elements are equal to their indices int MinimumRemovals(int a[], int N, int K) {     // Store the array as 1-based indexing     // Copy of first array     int b[N + 1];     for (int i = 0; i < N; i++) {         b[i + 1] = a[i];     }      // Initialize the dp-table with zeroes     int dp[N + 1];     memset(dp, 0, sizeof(dp));      // Iterate over the array and fill the dp-table     for (int i = 0; i < N; i++) {         for (int j = i + 1; j > 0; j--) {             dp[j] = max(dp[j], dp[j - 1] + ((b[i + 1] == j) ? 1 : 0));         }     }      // Check for the minimum removals     for (int j = N; j >= 0; j--) {         if (dp[j] >= K) {             return (N - j);         }     }     return -1; }  // Driver Code int main() {     int arr[] = { 5, 1, 3, 2, 3 };     int K = 2;     int N = sizeof(arr) / sizeof(arr[0]);     cout << MinimumRemovals(arr, N, K);      return 0; }  // this code is contributed by bhardwajji 
Java
import java.util.Arrays;  public class MinimumRemovals {    // Function to minimize the removals of   // array elements such that atleast K   // elements are equal to their indices   static int minimumRemovals(int a[], int N, int K)   {      // Store the array as 1-based indexing     // Copy of first array     int b[] = new int[N + 1];     for (int i = 0; i < N; i++) {       b[i + 1] = a[i];     }      // Initialize the dp-table with zeroes     int dp[] = new int[N + 1];     Arrays.fill(dp, 0);      // Iterate over the array and fill the dp-table     for (int i = 0; i < N; i++) {       for (int j = i + 1; j > 0; j--) {         dp[j] = Math.max(dp[j], dp[j - 1] + ((b[i + 1] == j) ? 1 : 0));       }     }      // Check for the minimum removals     for (int j = N; j >= 0; j--) {       if (dp[j] >= K) {         return (N - j);       }     }     return -1;   }    // Driver Code   public static void main(String[] args) {     int arr[] = { 5, 1, 3, 2, 3 };     int K = 2;     int N = arr.length;     System.out.println(minimumRemovals(arr, N, K));   } } 
Python
# Function to minimize the removals of # array elements such that atleast K # elements are equal to their indices def MinimumRemovals(a, N, K):     # Store the array as 1-based indexing     # Copy of first array     b = [0] * (N + 1)     for i in range(N):         b[i + 1] = a[i]      # Initialize the dp-table with zeroes     dp = [0] * (N + 1)      # Iterate over the array and fill the dp-table     for i in range(N):         for j in range(i + 1, 0, -1):             dp[j] = max(dp[j], dp[j - 1] + ((b[i + 1] == j)))      # Check for the minimum removals     for j in range(N, -1, -1):         if dp[j] >= K:             return (N - j)     return -1  # Driver Code arr = [5, 1, 3, 2, 3] K = 2 N = len(arr) print(MinimumRemovals(arr, N, K)) 
C#
using System;  public class Program {    // Function to minimize the removals of   // array elements such that atleast K   // elements are equal to their indices   public static int MinimumRemovals(int[] a, int N, int K)   {     // Store the array as 1-based indexing     // Copy of first array     int[] b = new int[N + 1];     for (int i = 0; i < N; i++) {       b[i + 1] = a[i];     }      // Initialize the dp-table with zeroes     int[] dp = new int[N + 1];     Array.Fill(dp, 0);      // Iterate over the array and fill the dp-table     for (int i = 0; i < N; i++) {       for (int j = i + 1; j > 0; j--) {         dp[j] = Math.Max(           dp[j],           dp[j - 1] + ((b[i + 1] == j) ? 1 : 0));       }     }      // Check for the minimum removals     for (int j = N; j >= 0; j--) {       if (dp[j] >= K) {         return (N - j);       }     }     return -1;   }    // Driver Code   public static void Main()   {     int[] arr = { 5, 1, 3, 2, 3 };     int K = 2;     int N = arr.Length;     Console.WriteLine(MinimumRemovals(arr, N, K));   } } // This code is contributed by user_dtewbxkn77n 
JavaScript
function minimumRemovals(a, N, K) {   // Store the array as 1-based indexing   // Copy of the first array   let b = new Array(N + 1);   for (let i = 0; i < N; i++) {     b[i + 1] = a[i];   }    // Initialize the dp-table with zeroes   let dp = new Array(N + 1).fill(0);    // Iterate over the array and fill the dp-table   for (let i = 0; i < N; i++) {     for (let j = i + 1; j > 0; j--) {       dp[j] = Math.max(dp[j], dp[j - 1] + (b[i + 1] === j ? 1 : 0));     }   }    // Check for the minimum removals   for (let j = N; j >= 0; j--) {     if (dp[j] >= K) {       return N - j;     }   }   return -1; }  // Driver Code let arr = [5, 1, 3, 2, 3]; let K = 2; let N = arr.length; console.log(minimumRemovals(arr, N, K)); 


Output: 

2


 

Time Complexity: O(N^2)
Auxiliary Space: O(N)


Next Article
Minimum number of elements to be removed such that the sum of the remaining elements is equal to k

K

kartikmodi
Improve
Article Tags :
  • Dynamic Programming
  • Mathematical
  • Blogathon
  • DSA
  • Arrays
  • Blogathon-2021
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Mathematical

Similar Reads

  • Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal
    Given an array arr[] consisting of N elements, the task is to find the minimum number of increments required to be performed on the given array such that after selecting any array element at any index and splitting its value to the other array elements makes all other N - 1 elements equal. Examples:
    6 min read
  • Count of Array elements to be divided by 2 to make at least K elements equal
    Given an integer array arr[] of size N, the task is to find the minimum number of array elements required to be divided by 2, to make at least K elements in the array equal.Example : Input: arr[] = {1, 2, 2, 4, 5}, N = 5, K = 3 Output: 1 Explanation: Dividing 4 by 2 modifies the array to {1, 2, 2, 2
    9 min read
  • Minimize count of divisions by D to obtain at least K equal array elements
    Given an array A[ ] of size N and two integers K and D, the task is to calculate the minimum possible number of operations required to obtain at least K equal array elements. Each operation involves replacing an element A[i] by A[i] / D. This operation can be performed any number of times. Examples:
    9 min read
  • Maximum value K such that array has at-least K elements that are >= K
    Given an array of positive integers, find maximum possible value K such that the array has at-least K elements that are greater than or equal to K. The array is unsorted and may contain duplicate values. Examples : Input: [2, 3, 4, 5, 6, 7] Output: 4 Explanation : 4 elements [4, 5, 6, 7] are greater
    14 min read
  • Minimum number of elements to be removed such that the sum of the remaining elements is equal to k
    Given an array arr[] of integers and an integer k, the task is to find the minimum number of integers that need to be removed from the array such that the sum of the remaining elements is equal to k. If we cannot get the required sum the print -1.Examples: Input: arr[] = {1, 2, 3}, k = 3 Output: 1 E
    8 min read
  • Minimize deletion or insertions of Array elements such that arr[i] have frequency as its value
    Given an array arr[] of length N, the task is to find the minimum number of operations to change the array such that each arr[i] occurs arr[i] times where in each operation either one element can be deleted from the array or one element can be inserted in the array. Examples: Input: N = 4, arr[ ] =
    7 min read
  • Maximum elements that can be removed from front of two arrays such that their sum is at most K
    Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
    15+ min read
  • Minimize replacements by integers up to K to make the sum of equidistant array elements from the end equal
    Given an array arr[] of even length N and an integer K, the task is to minimize the count of replacing array elements by an integer from the range [1, K] such that the sum of all pair of equidistant elements from the end of the array is equal. Examples: Input: arr[] = {1, 2, 4, 3}, K = 4Output: 1Exp
    9 min read
  • Remove minimum elements from the array such that 2*min becomes more than max
    Given an unsorted array, arr[]. The task is to find the minimum number of removals required such that twice the minimum element in the array is greater than or equal to the maximum in the array. Examples: Input: arr[] = [4, 5, 100, 9, 10, 11, 12, 15, 200]Output: 4Explanation: In the given array 4 el
    7 min read
  • Remove array elements to reduce frequency of each array element to at most K
    Given a sorted array arr[] of size N and an integer K, the task is to print the array by removing the minimum number of array elements to make frequency of each element at most K. Examples: Input: arr[] = { 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5 }, K = 3 Output: { 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5 } Ex
    14 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