Open In App

Colorful box arrangement with Removal Constraint

Given an array of colored boxes called arr, the task is to arrange these boxes to form a contiguous segment, where all the boxes have the same color. The segment should have a precise length of L. However, you’re allowed to remove a maximum of K boxes to make this arrangement possible. Is it possible to arrange the boxes according to a given condition?

Examples:



Input: [1, 1, 1, 2, 3, 1, 3, 3, 2], L = 4, K = 2
Output: True
Explanation: We can delete the boxes at index 3 and 4 i.e. 2 and 3 to achieve the result [1, 1, 1, 1, 3, 3, 2] which gives us the continuous segment of the same colored boxes from index 0 to 3.

Input: [4, 1, 2, 4, 1, 3, 2, 1, 4], L = 3, K = 4
Output: True
Explanation: We can delete the boxes at indices 2, 3, 5, 6 to achieve the result [4, 1, 1, 1, 4] which gives us the continuous segment of the same colored boxes from index 1 to 3, Here we also have the vector of color 4 which can be the potential segment of size 3 but for that, we would have to delete 6 elements (which is greater than K = 4) on indices (1, 2, 4, 5, 6, 7) to get [4, 4, 4].

Approach: To solve the problem follow the below steps:

Below is the implementation of the above idea:






// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
bool isPossible(vector<int>& arr, int L, int K)
{
    map<int, vector<int> > m;
 
    // Create a map of vector indices for each
    // unique color
    for (int i = 0; i < arr.size(); i++) {
        m[arr[i]].push_back(i);
    }
 
    // Iterate through the map's vectors to find
    // possible windows
    for (auto it : m) {
        vector<int> v = it.second;
 
        // Check if the vector size is enough
        // to form a window
        if (v.size() < L)
            continue;
 
        int i = 0, j = L - 1;
        while (j < v.size()) {
 
            // Calculate the number of elements
            // between indices
            int ele = v[j] - v[i] + 1;
 
            // Calculate how many elements need
            // to be deleted to fit the window
            ele -= L;
 
            // Check if deletions required are
            // within the allowed limit
            if (ele <= K)
 
                // We found a valid window
                return true;
            i++;
            j++;
        }
    }
 
    // No valid window found
    return false;
}
 
// Drivers code
int main()
{
    vector<int> arr = { 1, 1, 1, 2, 3, 1, 3, 3, 2 };
    int L = 4, K = 2;
 
    // Function Call
    if (isPossible(arr, L, K))
        cout << "True" << endl;
    else
        cout << "False" << endl;
}




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class Main {
    static boolean isPossible(List<Integer> arr, int L, int K) {
        Map<Integer, List<Integer>> m = new HashMap<>();
 
        // Create a map of list indices for each
        // unique color
        for (int i = 0; i < arr.size(); i++) {
            int color = arr.get(i);
            if (!m.containsKey(color)) {
                m.put(color, new ArrayList<>());
            }
            m.get(color).add(i);
        }
 
        // Iterate through the map's lists to find
        // possible windows
        for (Map.Entry<Integer, List<Integer>> entry : m.entrySet()) {
            List<Integer> v = entry.getValue();
 
            // Check if the list size is enough
            // to form a window
            if (v.size() < L)
                continue;
 
            int i = 0, j = L - 1;
            while (j < v.size()) {
                // Calculate the number of elements
                // between indices
                int ele = v.get(j) - v.get(i) + 1;
 
                // Calculate how many elements need
                // to be deleted to fit the window
                ele -= L;
 
                // Check if deletions required are
                // within the allowed limit
                if (ele <= K) {
                    // We found a valid window
                    return true;
                }
                i++;
                j++;
            }
        }
 
        // No valid window found
        return false;
    }
 
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>(List.of(1, 1, 1, 2, 3, 1, 3, 3, 2));
        int L = 4, K = 2;
 
        // Function Call
        if (isPossible(arr, L, K))
            System.out.println("True");
        else
            System.out.println("False");
    }
}




def is_possible(arr, L, K):
    m = {}
 
    # Create a dictionary of list indices for each
    # unique color
    for i in range(len(arr)):
        color = arr[i]
        if color not in m:
            m[color] = []
        m[color].append(i)
 
    # Iterate through the dictionary's lists to find
    # possible windows
    for color, v in m.items():
        # Check if the list size is enough
        # to form a window
        if len(v) < L:
            continue
 
        i, j = 0, L - 1
        while j < len(v):
            # Calculate the number of elements
            # between indices
            ele = v[j] - v[i] + 1
 
            # Calculate how many elements need
            # to be deleted to fit the window
            ele -= L
 
            # Check if deletions required are
            # within the allowed limit
            if ele <= K:
                # We found a valid window
                return True
            i += 1
            j += 1
 
    # No valid window found
    return False
 
arr = [1, 1, 1, 2, 3, 1, 3, 3, 2]
L = 4
K = 2
 
# Function Call
if is_possible(arr, L, K):
    print("True")
else:
    print("False")




using System;
using System.Collections.Generic;
 
class Program
{
    static bool IsPossible(List<int> arr, int L, int K)
    {
        Dictionary<int, List<int>> m =
          new Dictionary<int, List<int>>();
 
        // Create a dictionary of list indices for each
        // unique color
        for (int i = 0; i < arr.Count; i++)
        {
            if (!m.ContainsKey(arr[i]))
            {
                m[arr[i]] = new List<int>();
            }
            m[arr[i]].Add(i);
        }
 
        // Iterate through the dictionary's lists to find
        // possible windows
        foreach (var pair in m)
        {
            List<int> v = pair.Value;
 
            // Check if the list size is enough
            // to form a window
            if (v.Count < L)
                continue;
 
            int i = 0, j = L - 1;
            while (j < v.Count)
            {
                // Calculate the number of elements
                // between indices
                int ele = v[j] - v[i] + 1;
 
                // Calculate how many elements need
                // to be deleted to fit the window
                ele -= L;
 
                // Check if deletions required are
                // within the allowed limit
                if (ele <= K)
                {
                    // We found a valid window
                    return true;
                }
                i++;
                j++;
            }
        }
 
        // No valid window found
        return false;
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 1, 1, 1, 2, 3, 1, 3, 3, 2 };
        int L = 4, K = 2;
 
        // Function Call
        if (IsPossible(arr, L, K))
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
    }
}




function isPossible(arr, L, K) {
    const m = new Map();
 
    // Create a map of array indices for each
    // unique color
    for (let i = 0; i < arr.length; i++) {
        const color = arr[i];
        if (!m.has(color)) {
            m.set(color, []);
        }
        m.get(color).push(i);
    }
 
    // Iterate through the map's arrays to find
    // possible windows
    for (const [color, v] of m) {
        // Check if the array size is enough
        // to form a window
        if (v.length < L)
            continue;
 
        let i = 0, j = L - 1;
        while (j < v.length) {
            // Calculate the number of elements
            // between indices
            let ele = v[j] - v[i] + 1;
 
            // Calculate how many elements need
            // to be deleted to fit the window
            ele -= L;
 
            // Check if deletions required are
            // within the allowed limit
            if (ele <= K) {
                // We found a valid window
                return true;
            }
            i++;
            j++;
        }
    }
 
    // No valid window found
    return false;
}
 
const arr = [1, 1, 1, 2, 3, 1, 3, 3, 2];
const L = 4, K = 2;
 
// Function Call
if (isPossible(arr, L, K))
    console.log("True");
else
    console.log("False");

Output
True


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


Article Tags :