Open In App

Minimum Value X to Delete All Arrays

Last Updated : 16 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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));


Output

15








Time Complexity: O((N*M)*log (N*M))
Auxiliary Space: O(N*M)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads