Minimum length of X[] after removing at most K sub-arrays
Last Updated :
15 Nov, 2023
Given an array X[] of length N and an integer K. Then your task is to output minimum length of X[] after removing at most K number of sub-arrays, which satisfies the following conditions:
- Size of the sub-array must be greater than 1.
- First and last element of sub-array must be same.
Note: The sub-arrays which will satisfy the above condition will be non-intersecting. Formally, any sub-array which starts and ends with element A will not be overlapped with the any sub-array starting and ending with the element except A.
Examples:
Input: N = 9, X[] = {2, 3, 1, 1, 9, 34, 56, 9, 9}, K = 3
Output: 2
Explanation: There are two sub-arrays {1, 1} and {9, 34, 56, 9, 9}, which start and end with same element having size greater than 1. Since we can remove at most K = 3 sub-arrays, but two of such kind are present. Therefore, after removing these two sub-arrays, the minimum length of the remained X[] will be = 2.
Input: N = 4, X[] = {1, 2, 3, 4}, X = 2
Output: 4
Explanation: There are no sub-arrays such that it follows the given conditions. Therefore, we can’t remove any such sub-array. Hence the minimum length of X[] will be original as initial 4.
Approach: The problem can be solved by applying the Greedy approach.
We have to remove the K number of sub-arrays such that they follow the given conditions. As it is mentioned that sub-arrays must start and end with the same element. Thus we can get the first and last occurrence of an element from X[]. If the size of such sub-arrays is greater than 1 then store that length in a separate list. We can find the length of all such sub-arrays by iterating over X[] using a loop. After finding the length of all such sub-arrays, Sort them in any order(descending or ascending), and remove K number of subarrays of the biggest length from N, Formally, for minimizing the length of the remaining X[], we must remove the K sub-arrays having a maximum length. Now, the length of the remained X[] will be the minimum possible.
Below are the steps for the above approach:
- Create an ArrayList say list and copy the element of X[] into it.
- Create a HashMap say map for storing the length of sub-arrays.
- Run a loop from i = 0 to i < list size,
- Initialize a variable firstIndex = IndexOf(current_element)
- Initialize a variable lastIndex = lastIndexOf(current_element)
- Check if(firstIndex == lastIndex)
- else if the size is greater than 1, then put the length in Map
- map.put(current_element, lastIndex-firstIndex+1)
- Create an ArrayList say length for storing frequencies from the map.
- Sort the array length.
- Iterate the length array from index i = size of length array to i ≥ 0 and k > 0 and subtract K biggest lengths from N,
N = N – lengths.get(i) and decrement the value of K by 1.
- Print the value of N.
Below is the code for the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void remainedElements( int N, int K, vector< int >& X)
{
unordered_map< int , int > map;
for ( int i = 0; i < X.size(); i++) {
int firstIndex = find(X.begin(), X.end(), X[i]) - X.begin();
int lastIndex = find(X.rbegin(), X.rend(), X[i]) - X.rbegin();
lastIndex = X.size() - 1 - lastIndex;
if (firstIndex == lastIndex) {
continue ;
}
else {
map[X[i]] = lastIndex - firstIndex + 1;
}
}
vector< int > lengths;
for ( auto it = map.begin(); it != map.end(); ++it) {
lengths.push_back(it->second);
}
sort(lengths.begin(), lengths.end());
for ( int i = lengths.size() - 1; i >= 0 && K > 0;
i--) {
N -= lengths[i];
K--;
}
cout << N << endl;
}
int main()
{
int N = 9;
int K = 3;
vector< int > X = { 12, 3, 1, 1, 2, 2, 2, 2, 5 };
remainedElements(N, K, X);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int N = 9 ;
int K = 3 ;
int X[] = { 12 , 3 , 1 , 1 , 2 , 2 , 2 , 2 , 5 };
RemainedElements(N, K, X);
}
static void RemainedElements( int N, int K, int [] X)
{
ArrayList<Integer> list = new ArrayList<>();
for ( int x : X)
list.add(x);
HashMap<Integer, Integer> map = new HashMap<>();
for ( int i = 0 ; i < list.size(); i++) {
int firstIndex = list.indexOf(list.get(i));
int lastIndex = list.lastIndexOf(list.get(i));
if (firstIndex == lastIndex) {
continue ;
}
else {
map.put(list.get(i),
lastIndex - firstIndex + 1 );
}
}
ArrayList<Integer> lengths
= new ArrayList<>(map.values());
lengths.sort( null );
for ( int i = lengths.size() - 1 ; i >= 0 && K > 0 ;
i--) {
N = N - lengths.get(i);
K--;
}
System.out.println(N);
}
}
|
Python3
import collections
def remainedElements(N, K, X):
map = collections.defaultdict( int )
for i in range ( len (X)):
firstIndex = X.index(X[i])
lastIndex = len (X) - 1 - X[:: - 1 ].index(X[i])
if firstIndex = = lastIndex:
continue
else :
map [X[i]] = lastIndex - firstIndex + 1
lengths = list ( map .values())
lengths.sort()
for i in range ( len (lengths) - 1 , - 1 , - 1 ):
N - = lengths[i]
K - = 1
if K = = 0 :
break
print (N)
N = 9
K = 3
X = [ 12 , 3 , 1 , 1 , 2 , 2 , 2 , 2 , 5 ]
remainedElements(N, K, X)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
static void RemainedElements( int N, int K, List< int > X)
{
Dictionary< int , int > map = new Dictionary< int , int >();
for ( int i = 0; i < X.Count; i++)
{
int firstIndex = X.IndexOf(X[i]);
int lastIndex = X.LastIndexOf(X[i]);
if (firstIndex == lastIndex)
{
continue ;
}
else
{
map[X[i]] = lastIndex - firstIndex + 1;
}
}
List< int > lengths = new List< int >();
foreach ( var kvp in map)
{
lengths.Add(kvp.Value);
}
lengths.Sort();
for ( int i = lengths.Count - 1; i >= 0 && K > 0; i--)
{
N -= lengths[i];
K--;
}
Console.WriteLine(N);
}
public static void Main()
{
int N = 9;
int K = 3;
List< int > X = new List< int > { 12, 3, 1, 1, 2, 2, 2, 2, 5 };
RemainedElements(N, K, X);
}
}
|
Javascript
function GFG(N, K, X) {
const map = new Map();
for (let i = 0; i < X.length; i++) {
const firstIndex = X.indexOf(X[i]);
const lastIndex = X.lastIndexOf(X[i]);
if (firstIndex === lastIndex) {
continue ;
} else {
map.set(X[i], lastIndex - firstIndex + 1);
}
}
const lengths = Array.from(map.values());
lengths.sort((a, b) => a - b);
for (let i = lengths.length - 1; i >= 0 && K > 0; i--) {
N -= lengths[i];
K--;
}
console.log(N);
}
function main() {
const N = 9;
const K = 3;
const X = [12, 3, 1, 1, 2, 2, 2, 2, 5];
GFG(N, K, X);
}
main();
|
Time Complexity: O(N * LogN)
Space Complexity: O(N)
Share your thoughts in the comments
Please Login to comment...