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;
// Method for printing minimum length
void remainedElements(int N, int K, vector<int>& X)
{
// Map initialized for storing
// lentgth of sub subarrays along
// with the element
unordered_map<int, int> map;
// Loop for initilizing map with
// length of such sub-arrays
for (int i = 0; i < X.size(); i++) {
// Getting first index of
// current element
int firstIndex = find(X.begin(), X.end(), X[i]) - X.begin();
// Getting last index of
// current element
int lastIndex = find(X.rbegin(), X.rend(), X[i]) - X.rbegin();
// Convert last index to
// actual index in X
lastIndex = X.size() - 1 - lastIndex;
// If firstIndex is equal to
// Last index Formally, there
// is only one element of such
// value Then ignore it, can't
// be considered as sub-array
// because size must be
// greater than 1
if (firstIndex == lastIndex) {
continue;
}
// If size is greater than 1,
// Then putting length in Map
else {
map[X[i]] = lastIndex - firstIndex + 1;
}
}
// Vector for storing lengths
// from map
vector<int> lengths;
for (auto it = map.begin(); it != map.end(); ++it) {
lengths.push_back(it->second);
}
// Sorting sub-array's length
sort(lengths.begin(), lengths.end());
// Removing K number of such
// sub-arrays with biggest size
// formally, Iterating backward
// in list of sorted lengths
for (int i = lengths.size() - 1; i >= 0 && K > 0;
i--) {
N -= lengths[i];
K--;
}
// Printing minimum length after
// removing such K sub-arrays
cout << N << endl;
}
// Driver Function
int main()
{
// Inputs
int N = 9;
int K = 3;
vector<int> X = { 12, 3, 1, 1, 2, 2, 2, 2, 5 };
// Function call for printing
// length after removing such
// K number of sub-arrays
remainedElements(N, K, X);
return 0;
}
Java
// java code to implement the approach
import java.util.*;
public class GFG {
// Driver Function
public static void main(String[] args)
{
// Inputs
int N = 9;
int K = 3;
int X[] = { 12, 3, 1, 1, 2, 2, 2, 2, 5 };
// Function call for printing
// length after removing such
// K number of sub-arrays
RemainedElements(N, K, X);
}
// Method for printing minimum length
static void RemainedElements(int N, int K, int[] X)
{
// ArrayList for storing element
// of X[] because it will be
// convienient to find First and
// last index of an element using
// in-built func. such as
// indexOf(), lastIndexOf()
ArrayList<Integer> list = new ArrayList<>();
// Loop for copying elements
// from X[] to list
for (int x : X)
list.add(x);
// Map initialized for storing
// lentgth of sub subarrays along
// with the element
HashMap<Integer, Integer> map = new HashMap<>();
// Loop for initilizing map with
// length of such sub-arrays
for (int i = 0; i < list.size(); i++) {
// Getting first index of
// current element
int firstIndex = list.indexOf(list.get(i));
// Getting last index of
// current element
int lastIndex = list.lastIndexOf(list.get(i));
// If firstIndex is equal to
// Last index Formally, there
// is only one element of such
// value Then ignore it, can't
// be considered as sub-array
// because size must be
// greater than 1
if (firstIndex == lastIndex) {
continue;
}
// If size is greater than 1,
// Then putting length in Map
else {
map.put(list.get(i),
lastIndex - firstIndex + 1);
}
}
// List for storing lengths
// from map
ArrayList<Integer> lengths
= new ArrayList<>(map.values());
// Sorting sub-array's length
lengths.sort(null);
// Removing K number of such
// sub-arrays with biggest size
// formally, Iterating backward
// in list of sorted lengths
for (int i = lengths.size() - 1; i >= 0 && K > 0;
i--) {
N = N - lengths.get(i);
K--;
}
// Printing minimum length after
// removing such K sub-arrays
System.out.println(N);
}
}
Python3
import collections
# Method for printing minimum length
def remainedElements(N, K, X):
# Map initialized for storing
# lentgth of sub subarrays along
# with the element
map = collections.defaultdict(int)
# Loop for initilizing map with
# length of such sub-arrays
for i in range(len(X)):
# Getting first index of
# current element
firstIndex = X.index(X[i])
# Getting last index of
# current element
lastIndex = len(X) - 1 - X[::-1].index(X[i])
# If firstIndex is equal to
# Last index Formally, there
# is only one element of such
# value Then ignore it, can't
# be considered as sub-array
# because size must be
# greater than 1
if firstIndex == lastIndex:
continue
# If size is greater than 1,
# Then putting length in Map
else:
map[X[i]] = lastIndex - firstIndex + 1
# Vector for storing lengths
# from map
lengths = list(map.values())
# sorting sub-array's length
lengths.sort()
# Removing K number of such
# sub-arrays with biggest size
# formally, Iterating backward
# in list of sorted lengths
for i in range(len(lengths) - 1, -1, -1):
N -= lengths[i]
K -= 1
if K == 0:
break
# Printing minimum length after
# removing such K sub-arrays
print(N)
# Driver Function
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
{
// Method for printing minimum length
static void RemainedElements(int N, int K, List<int> X)
{
// Dictionary initialized for storing
// length of sub subarrays along with the element
Dictionary<int, int> map = new Dictionary<int, int>();
// Loop for initializing map with
// the length of such sub-arrays
for (int i = 0; i < X.Count; i++)
{
// Getting first index of current element
int firstIndex = X.IndexOf(X[i]);
// Getting last index of current element
int lastIndex = X.LastIndexOf(X[i]);
// If firstIndex is equal to
// last index, there is only one element of such value
// Then ignore it, it can't be considered as sub-array
// because size must be greater than 1
if (firstIndex == lastIndex)
{
continue;
}
// If size is greater than 1,
// then put length in the map
else
{
map[X[i]] = lastIndex - firstIndex + 1;
}
}
// List for storing lengths from map
List<int> lengths = new List<int>();
foreach (var kvp in map)
{
lengths.Add(kvp.Value);
}
// Sorting sub-array's length
lengths.Sort();
// Removing K number of such sub-arrays with the biggest size
// Formally, iterating backward in the list of sorted lengths
for (int i = lengths.Count - 1; i >= 0 && K > 0; i--)
{
N -= lengths[i];
K--;
}
// Printing the minimum length after removing such K sub-arrays
Console.WriteLine(N);
}
// Driver Function
public static void Main()
{
// Inputs
int N = 9;
int K = 3;
List<int> X = new List<int> { 12, 3, 1, 1, 2, 2, 2, 2, 5 };
// Function call for printing
// length after removing such
// K number of sub-arrays
RemainedElements(N, K, X);
}
}
JavaScript
function GFG(N, K, X) {
// Map initialized for storing the length of sub-arrays along with
// the element
const map = new Map();
// Loop for initializing the map with
// the length of sub-arrays
for (let i = 0; i < X.length; i++) {
// Getting the first index of current element
const firstIndex = X.indexOf(X[i]);
// Getting the last index of current element
const lastIndex = X.lastIndexOf(X[i]);
// If firstIndex is equal to the last index
// ignore it (size must be greater than 1)
if (firstIndex === lastIndex) {
continue;
} else {
// Calculate the length and store it in the map
map.set(X[i], lastIndex - firstIndex + 1);
}
}
// Get an array of sub-array lengths from the map
const lengths = Array.from(map.values());
// Sort the sub-array lengths
lengths.sort((a, b) => a - b);
// Removing K number of sub-arrays with biggest size
for (let i = lengths.length - 1; i >= 0 && K > 0; i--) {
N -= lengths[i];
K--;
}
// Printing the minimum length after removing K sub-arrays
console.log(N);
}
// Driver Function
function main() {
// Inputs
const N = 9;
const K = 3;
const X = [12, 3, 1, 1, 2, 2, 2, 2, 5];
// Function call for calculating the minimum length after
// removing K sub-arrays
GFG(N, K, X);
}
main();
Time Complexity: O(N * LogN)
Space Complexity: O(N)
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