Open In App

Colorful box arrangement with Removal Constraint

Last Updated : 26 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Create a map that associates each unique color (number) with the indices where it occurs in the array.
  • For each unique color, check if there are enough occurrences to form a window of size L. If not, skip to the next color.
  • While iterating through the indices of a color we have to maintain the window size of L so we take the current index as ‘0’ initially and the last index as L-1 and while iterating keep on incrementing them by one to maintain the window size of L, then calculate the number of elements between the current and last index in the window. This will help us understand how many elements need to be deleted to fit the window size.
  • Check if the number of deletions required to fit the window is within the allowed limit K. If so, return true, indicating that there exists a window of required length and deletions.
  • If no valid window is found for any color, return false.

Below is the implementation of the above idea:

C++




// 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;
}


Java




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


Python3




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


C#




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


Javascript




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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads