Minimum Value X to Delete All Arrays
Last Updated :
23 Jul, 2025
Given 2d array A[][] of size N*M. Your Task is to choose the minimum possible number X to perform the following operation. In one operation choose any array i from N arrays and delete the first element, if it is less than X, and increase X by 1. Keep performing this operation until the array becomes empty. After that choose another array from the remaining arrays and perform the same operation until all N arrays become empty. The task for this problem is to minimize the value of X that is chosen initially.
Examples:
Input: A[][] = {{10, 15, 8}, {12, 11}}
Output: 13
Explanation: In first operation remove {12, 11}
- Current X = 13 as the first element is 12 which is less than X = 13 delete first element then increment X by 1. X becomes 14.
- Current X = 14 as the first element is 11 which is less than X = 14 delete first element then increment X by 1 . X becomes 15.
In second operation remove {10, 15, 8}
- Current X = 15 as the first element is 10 which is less than X = 15 delete first element then increment X by 1. X becomes 16
- Current X = 16 as the first element is 15 which is less than X = 16 delete first element then increment X by 1. X becomes 17
- Current X = 17 as the first element is 8 which is less than X = 17 delete first element then increment X by 1. X becomes 18
so X = 13 is the minimum value chosen for X to delete all arrays
Input: A[] = {{42}}
Output: 43
Explanation:
Chose X = 43 so In first operation remove {42}
- Current X = 43 as the first element is 42 which is less than X = 43 delete first element then increment X by 1. X becomes 44
- so X = 43 is the minimum value chosen for X to delete all arrays
Efficient Approach: To solve the problem follow the below idea:
Binary Search can be used to solve this problem and the range of binary search will be 1 to maxElementOfAllArrays(A[][]) + 1. f(X) is monotonic function represents whether chosen X will remove all elements of array A[][] or not. it is of the form FFFFFFFFTTTTTTT. we have to find when the first time function becomes true using Binary Search. We need to sort Given N arrays according to maximum X they need to delete all elements from that array and merge all arrays together into one array to perform all the operations together.
Below are the steps for the above approach:
- Create 2d array V[][] of size N.
- Sort the array according to maximum operations required in it which is tracked by maxi variable. push first maximum X required to delete all elements of ith array then all elements of i'th array in V[][].
- Declare another array B[] to push all arrays in sorted order.
- Set low and high range of binary serach.
- ispos(mid) function used to check whether X = mid is enough to delete all elements from array B[].
- Run while loop till high and low are not equal.
- In while loop find middle element and store it in mid variable.
- Check if that mid is enough to delete all elements from array B[] using ispos() function. If it is true then set high = mid else low = mid + 1.
- After loop ends if ispos() true for low then return low else return high.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if mid is enough
// to delte all elements from B[]
bool ispos(int mid, vector<int> B, int N)
{
// iterating over all elements of B
for (int i = 0; i < N; i++) {
// if i'th element can be deleted increment X = mid
// by 1
if (B[i] < mid)
mid++;
// if it is not possible to empty the array B[]
// return false
else
return false;
}
// if it is possible to empty array B[]
// then return true
return true;
}
// Function to Find Minimum value X chosen to delete all
// arrays
int findMinM(vector<vector<int> >& A, int N)
{
// Declaring N empty vectors
vector<vector<int> > V(N);
// Declare B to unify array
vector<int> B;
for (int i = 0; i < N; i++) {
// tracking maximum value required to delete jth
// element of i'th array
int maxi = 0;
// iterate over all Elements of arrays
for (int j = 0; j < A[i].size(); j++) {
// updating maxi A[i][j]th element requires
// A[i][j] + 1 - j to delte itself
maxi = max(maxi, A[i][j] + 1 - j);
}
// pushing maxi value in front of array V for
// sorting according to first element
V[i].push_back(maxi);
// inserting all elements in ith array
for (int k = 0; k < A[i].size(); k++) {
V[i].push_back(A[i][k]);
}
}
// sorting array V
sort(V.begin(), V.end());
// iterate over all elements to push all elements of
// array A[][] with sorted order in B[]
for (int i = 0; i < V.size(); i++) {
for (int j = 1; j < V[i].size(); j++) {
B.push_back(V[i][j]);
}
}
// Range of binary search
int low = 1, high = 1e9;
// Running loop till high
// is not equal to low
while (high - low > 1) {
// mid is average of low and high
int mid = (low + high) / 2;
// Checking test function
if (ispos(mid, B, B.size())) {
high = mid;
}
else {
low = mid + 1;
}
}
// Checking whether low can be answer
if (ispos(low, B, B.size()))
return low;
// If not then it is high
else
return high;
}
// Driver Code
int32_t main()
{
// Input 1
int N = 2;
vector<vector<int> > A = { { 10, 15, 18 }, { 12, 11 } };
// Function Call
cout << findMinM(A, N) << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MinDeletionToEmptyArrays {
// Function to check if mid is enough to delete all elements from B[]
static boolean isPos(int mid, List<Integer> B, int N) {
for (int i = 0; i < N; i++) {
if (B.get(i) < mid)
mid++;
else
return false;
}
return true;
}
// Function to find the minimum value X chosen to delete all arrays
static int findMinM(List<List<Integer>> A, int N) {
List<List<Integer>> V = new ArrayList<>(N);
// Declare B to unify array
List<Integer> B = new ArrayList<>();
for (int i = 0; i < N; i++) {
int maxi = 0;
for (int j = 0; j < A.get(i).size(); j++) {
maxi = Math.max(maxi, A.get(i).get(j) + 1 - j);
}
V.add(new ArrayList<>());
V.get(i).add(maxi);
V.get(i).addAll(A.get(i));
}
// Sorting array V
Collections.sort(V, (a, b) -> a.get(0) - b.get(0));
// Iterate over all elements to push all elements of array A[][] with sorted order in B[]
for (int i = 0; i < V.size(); i++) {
B.addAll(V.get(i).subList(1, V.get(i).size()));
}
// Range of binary search
int low = 1, high = (int)1e9;
// Running loop until high is not equal to low
while (high - low > 1) {
// mid is the average of low and high
int mid = (low + high) / 2;
// Checking test function
if (isPos(mid, B, B.size())) {
high = mid;
} else {
low = mid + 1;
}
}
// Checking whether low can be the answer
if (isPos(low, B, B.size()))
return low;
else
// If not, then it is high
return high;
}
// Driver Code
public static void main(String[] args) {
// Input
int N = 2;
List<List<Integer>> A = List.of(
List.of(10, 15, 18),
List.of(12, 11)
);
// Function Call
System.out.println(findMinM(A, N));
}
}
// This code is contributed by shivamgupta310570
Python
def ispos(mid, B, N):
"""
Function to check if mid is enough to delete all elements from B[]
"""
for i in range(N):
if B[i] < mid:
mid += 1
else:
return False
return True
def findMinM(A, N):
"""
Function to Find Minimum value X chosen to delete all arrays
"""
# Declaring N empty lists
V = [[] for _ in range(N)]
# Declare B to unify array
B = []
for i in range(N):
# tracking maximum value required to delete jth element of ith array
maxi = 0
# iterate over all Elements of arrays
for j in range(len(A[i])):
# updating maxi A[i][j]th element requires A[i][j] + 1 - j to delete itself
maxi = max(maxi, A[i][j] + 1 - j)
# pushing maxi value in front of array V for sorting according to the first element
V[i].append(maxi)
# inserting all elements in the ith array
V[i].extend(A[i])
# sorting array V
V.sort()
# iterate over all elements to push all elements of array A[][] with sorted order in B[]
for i in range(len(V)):
B.extend(V[i][1:])
# Range of binary search
low, high = 1, 10**9
# Running loop until high is not equal to low
while high - low > 1:
# mid is the average of low and high
mid = (low + high) // 2
# Checking the test function
if ispos(mid, B, len(B)):
high = mid
else:
low = mid + 1
# Checking whether low can be the answer
if ispos(low, B, len(B)):
return low
# If not, then it is high
else:
return high
# Driver Code
if __name__ == "__main__":
# Input 1
N = 2
A = [[10, 15, 18], [12, 11]]
# Function Call
print(findMinM(A, N))
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution
{
// Function to check if mid is enough to delete all elements from B[]
public static bool IsPositive(int mid, List<int> B, int N)
{
// Iterating over all elements of B
for (int i = 0; i < N; i++)
{
// If i'th element can be deleted increment mid by 1
if (B[i] < mid)
mid++;
// If it is not possible to empty the array B[]
// return false
else
return false;
}
// If it is possible to empty array B[]
// then return true
return true;
}
// Function to Find Minimum value mid chosen to delete all arrays
public static int FindMinM(List<List<int>> A, int N)
{
// Declaring N empty lists
List<List<int>> V = new List<List<int>>(N);
// Declare B to unify array
List<int> B = new List<int>();
for (int i = 0; i < N; i++)
{
int maxi = 0;
// Iterate over all elements of arrays
for (int j = 0; j < A[i].Count; j++)
{
maxi = Math.Max(maxi, A[i][j] + 1 - j);
}
// Pushing maxi value in front of list V for sorting
V.Add(new List<int> { maxi });
// Inserting all elements in the list
V[i].AddRange(A[i]);
}
// Sorting list V based on the first element of each sublist
V = V.OrderBy(x => x[0]).ToList();
// Iterate over all elements to push all elements of array A[][]
// with sorted order in B[]
foreach (var sublist in V)
{
B.AddRange(sublist.Skip(1));
}
// Binary search range
int low = 1, high = 1000000000; // 1e9 in C++
while (high - low > 1)
{
int mid = (low + high) / 2;
// Checking test function
if (IsPositive(mid, B, B.Count))
high = mid;
else
low = mid + 1;
}
// Checking whether low can be the answer
if (IsPositive(low, B, B.Count))
return low;
else
return high;
}
// Driver Code
public static void Main(string[] args)
{
// Input 1
int N = 2;
List<List<int>> A = new List<List<int>> { new List<int> { 10, 15, 18 }, new List<int> { 12, 11 } };
// Function Call
Console.WriteLine(FindMinM(A, N));
}
}
// This code is contributed by rambabugupka
JavaScript
function isPos(mid, B, N) {
/**
* Function to check if mid is enough to delete all elements from B[]
*/
for (let i = 0; i < N; i++) {
if (B[i] < mid) {
mid++;
} else {
return false;
}
}
return true;
}
function findMinM(A, N) {
/**
* Function to Find Minimum value X chosen to delete all arrays
*/
// Declaring N empty arrays
const V = new Array(N).fill(null).map(() => []);
// Declare B to unify array
const B = [];
for (let i = 0; i < N; i++) {
// tracking maximum value required to delete jth element of ith array
let maxi = 0;
// iterate over all Elements of arrays
for (let j = 0; j < A[i].length; j++) {
// updating maxi A[i][j]th element requires A[i][j] + 1 - j to delete itself
maxi = Math.max(maxi, A[i][j] + 1 - j);
}
// pushing maxi value in front of array V for sorting according to the first element
V[i].push(maxi);
// inserting all elements in the ith array
V[i].push(...A[i]);
}
// sorting array V
V.sort((a, b) => a[0] - b[0]);
// iterate over all elements to push all elements of array A[][] with sorted order in B[]
for (let i = 0; i < V.length; i++) {
B.push(...V[i].slice(1));
}
// Range of binary search
let low = 1;
let high = 1e9;
// Running loop until high is not equal to low
while (high - low > 1) {
// mid is the average of low and high
const mid = Math.floor((low + high) / 2);
// Checking the test function
if (isPos(mid, B, B.length)) {
high = mid;
} else {
low = mid + 1;
}
}
// Checking whether low can be the answer
if (isPos(low, B, B.length)) {
return low;
}
// If not, then it is high
else {
return high;
}
}
// Driver Code
// Input
const N = 2;
const A = [
[10, 15, 18],
[12, 11]
];
// Function Call
console.log(findMinM(A, N));
Time Complexity: O((N*M)*log (N*M))
Auxiliary Space: O(N*M)
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