Minimize count of array elements to be removed such that at least K elements are equal to their index values
Last Updated :
23 Jul, 2025
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>
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem