Shortest subarray to be removed to make all Array elements unique
Last Updated :
12 Jul, 2025
Given an array arr[] containing N elements, the task is to remove a subarray of minimum possible length from the given array such that all remaining elements are distinct. Print the minimum possible length of the subarray.
Examples:
Input: N = 5, arr[] = {1, 2, 1, 2, 3}
Output: 2
Explanation:
Remove the sub array {2, 1} to make the elements distinct.
Input: N = 5, arr[] = {1, 2, 3, 4, 5}
Output: 0
Explanation:
Elements are already distinct.
Naive Approach: The naive approach for this problem is to simply check for all the possible subarrays and find the length of the smallest subarray after removal of which all the elements in the array become distinct.
Time complexity: O(N3)
Efficient Approach:
- Let ans be the length of the minimum subarray that on removing from the given array, makes the elements of the array unique.
- We can easily observe that if all array elements become distinct after removing a subarray of length ans, then this condition is also true for all values greater than ans.
- This means that the solution for this problem is a monotonically increasing function and we can apply binary search on the answer.
- Now, for a particular length K of subarray, we can check if elements of prefix and suffix of all sub arrays of length K are distinct or not.
- We can do this by using a sliding window technique.
- Use a hash map to store the frequencies of elements in prefix and suffix, on moving the window forward, increment frequency of the last element of prefix and decrement frequency of the first element of suffix.
Below is the implementation of the above approach:
C++
// C++ program to make array elements
// distinct by removing at most
// one subarray of minimum length
#include <bits/stdc++.h>
using namespace std;
// Function to check if elements of
// Prefix and suffix of each sub array
// of size K are distinct or not
bool check(int a[], int n, int k)
{
// Hash map to store frequencies of
// elements of prefix and suffix
map<int, int> m;
// Variable to store number of
// occurrences of an element other
// than one
int extra = 0;
// Adding frequency of elements of suffix
// to hash for subarray starting from first
// index
// There is no prefix for this sub array
for (int i = k; i < n; i++)
m[a[i]]++;
// Counting extra elements in current Hash
// map
for (auto x : m)
extra += x.second - 1;
// If there are no extra elements return
// true
if (extra == 0)
return true;
// Check for remaining sub arrays
for (int i = 1; i + k - 1 < n; i++) {
// First element of suffix is now
// part of subarray which is being
// removed so, check for extra elements
if (m[a[i + k - 1]] > 1)
extra--;
// Decrement frequency of first
// element of the suffix
m[a[i + k - 1]]--;
// Increment frequency of last
// element of the prefix
m[a[i - 1]]++;
// Check for extra elements
if (m[a[i - 1]] > 1)
extra++;
// If there are no extra elements
// return true
if (extra == 0)
return true;
}
return false;
}
// Function for calculating minimum
// length of the subarray, which on
// removing make all elements distinct
int minlength(int a[], int n)
{
// Possible range of length of subarray
int lo = 0, hi = n + 1;
int ans = 0;
// Binary search to find minimum ans
while (lo < hi) {
int mid = (lo + hi) / 2;
if (check(a, n, mid)) {
ans = mid;
hi = mid;
}
else
lo = mid + 1;
}
return ans;
}
// Driver code
int main()
{
int a[5] = { 1, 2, 1, 2, 3 };
int n = sizeof(a) / sizeof(int);
cout << minlength(a, n);
}
Java
// Java program to make array elements
// pairwise distinct by removing at most
// one subarray of minimum length
import java.util.*;
import java.lang.*;
class GFG{
// Function to check if elements of
// Prefix and suffix of each sub array
// of size K are pairwise distinct or not
static boolean check(int a[], int n, int k)
{
// Hash map to store frequencies of
// elements of prefix and suffix
Map<Integer, Integer> m = new HashMap<>();
// Variable to store number of
// occurrences of an element other
// than one
int extra = 0;
// Adding frequency of elements of suffix
// to hash for subarray starting from first
// index
// There is no prefix for this sub array
for(int i = k; i < n; i++)
m.put(a[i], m.getOrDefault(a[i], 0) + 1);
// Counting extra elements in current Hash
// map
for(Integer x : m.values())
extra += x - 1;
// If there are no extra elements return
// true
if (extra == 0)
return true;
// Check for remaining sub arrays
for(int i = 1; i + k - 1 < n; i++)
{
// First element of suffix is now
// part of subarray which is being
// removed so, check for extra elements
if (m.get(a[i + k - 1]) > 1)
extra--;
// Decrement frequency of first
// element of the suffix
m.put(a[i + k - 1],
m.get(a[i + k - 1]) - 1);
// Increment frequency of last
// element of the prefix
m.put(a[i - 1], m.get(a[i - 1]) + 1);
// Check for extra elements
if (m.get(a[i - 1]) > 1)
extra++;
// If there are no extra elements
// return true
if (extra == 0)
return true;
}
return false;
}
// Function for calculating minimum
// length of the subarray, which on
// removing make all elements pairwise
// distinct
static int minlength(int a[], int n)
{
// Possible range of length of subarray
int lo = 0, hi = n + 1;
int ans = 0;
// Binary search to find minimum ans
while (lo < hi)
{
int mid = (lo + hi) / 2;
if (check(a, n, mid))
{
ans = mid;
hi = mid;
}
else
lo = mid + 1;
}
return ans;
}
// Driver Code
public static void main (String[] args)
{
int a[] = { 1, 2, 1, 2, 3 };
int n = a.length;
System.out.println(minlength(a, n));
}
}
// This code is contributed by offbeat
Python3
# Python3 program to make array elements
# pairwise distinct by removing at most
# one subarray of minimum length
from collections import defaultdict
# Function to check if elements of
# Prefix and suffix of each sub array
# of size K are pairwise distinct or not
def check(a, n, k):
# Hash map to store frequencies of
# elements of prefix and suffix
m = defaultdict(int)
# Variable to store number of
# occurrences of an element other
# than one
extra = 0
# Adding frequency of elements of suffix
# to hash for subarray starting from first
# index
# There is no prefix for this sub array
for i in range(k, n):
m[a[i]] += 1
# Counting extra elements in current Hash
# map
for x in m:
extra += m[x] - 1
# If there are no extra elements return
# true
if (extra == 0):
return True
# Check for remaining sub arrays
for i in range(1, i + k - 1 < n):
# First element of suffix is now
# part of subarray which is being
# removed so, check for extra elements
if (m[a[i + k - 1]] > 1):
extra -= 1
# Decrement frequency of first
# element of the suffix
m[a[i + k - 1]] -= 1
# Increment frequency of last
# element of the prefix
m[a[i - 1]] += 1
# Check for extra elements
if (m[a[i - 1]] > 1):
extra += 1
# If there are no extra elements
# return true
if (extra == 0):
return True
return False
# Function for calculating minimum
# length of the subarray, which on
# removing make all elements pairwise
# distinct
def minlength(a, n):
# Possible range of length of subarray
lo = 0
hi = n + 1
ans = 0
# Binary search to find minimum ans
while (lo < hi):
mid = (lo + hi) // 2
if (check(a, n, mid)):
ans = mid
hi = mid
else:
lo = mid + 1
return ans
# Driver code
if __name__ == "__main__":
a = [ 1, 2, 1, 2, 3 ]
n = len(a)
print(minlength(a, n))
# This code is contributed by chitranayal
C#
// C# program to make array elements
// pairwise distinct by removing at most
// one subarray of minimum length
using System;
using System.Collections.Generic;
class GFG{
// Function to check if elements of
// Prefix and suffix of each sub array
// of size K are pairwise distinct or not
static bool check(int []a, int n, int k)
{
// Hash map to store frequencies of
// elements of prefix and suffix
Dictionary<int,
int> m = new Dictionary<int,
int>();
// Variable to store number of
// occurrences of an element other
// than one
int extra = 0;
// Adding frequency of elements of suffix
// to hash for subarray starting from first
// index
// There is no prefix for this sub array
for(int i = k; i < n; i++)
if(m.ContainsKey(a[i]))
m[a[i]] = m[a[i]] + 1;
else
m.Add(a[i], 1);
// Counting extra elements in current Hash
// map
foreach(int x in m.Keys)
extra += m[x] - 1;
// If there are no extra elements return
// true
if (extra == 0)
return true;
// Check for remaining sub arrays
for(int i = 1; i + k - 1 < n; i++)
{
// First element of suffix is now
// part of subarray which is being
// removed so, check for extra elements
if (m[a[i + k - 1]] > 1)
extra--;
// Decrement frequency of first
// element of the suffix
m[a[i + k - 1]] = m[a[i + k - 1]] - 1;
// Increment frequency of last
// element of the prefix
m[a[i - 1]] = m[a[i - 1]] + 1;
// Check for extra elements
if (m[a[i - 1]] > 1)
extra++;
// If there are no extra elements
// return true
if (extra == 0)
return true;
}
return false;
}
// Function for calculating minimum
// length of the subarray, which on
// removing make all elements pairwise
// distinct
static int minlength(int []a, int n)
{
// Possible range of length of subarray
int lo = 0, hi = n + 1;
int ans = 0;
// Binary search to find minimum ans
while (lo < hi)
{
int mid = (lo + hi) / 2;
if (check(a, n, mid))
{
ans = mid;
hi = mid;
}
else
lo = mid + 1;
}
return ans;
}
// Driver Code
public static void Main(String[] args)
{
int []a = { 1, 2, 1, 2, 3 };
int n = a.Length;
Console.WriteLine(minlength(a, n));
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// Javascript program to make array elements
// pairwise distinct by removing at most
// one subarray of minimum length
// Function to check if elements of
// Prefix and suffix of each sub array
// of size K are pairwise distinct or not
function check(a, n, k)
{
// Hash map to store frequencies of
// elements of prefix and suffix
let m = new Map();
// Variable to store number of
// occurrences of an element other
// than one
let extra = 0;
// Adding frequency of elements of suffix
// to hash for subarray starting from first
// index
// There is no prefix for this sub array
for(let i = k; i < n; i++)
m.set(a[i], m.get(a[i])==null? 1 :m.get(a[i])+ 1);
// Counting extra elements in current Hash
// map
for(let x of m.values())
extra += x - 1;
// If there are no extra elements return
// true
if (extra == 0)
return true;
// Check for remaining sub arrays
for(let i = 1; i + k - 1 < n; i++)
{
// First element of suffix is now
// part of subarray which is being
// removed so, check for extra elements
if (m.get(a[i + k - 1]) > 1)
extra--;
// Decrement frequency of first
// element of the suffix
m.set(a[i + k - 1],
m.get(a[i + k - 1]) - 1);
// Increment frequency of last
// element of the prefix
m.set(a[i - 1], m.get(a[i - 1]) + 1);
// Check for extra elements
if (m.get(a[i - 1]) > 1)
extra++;
// If there are no extra elements
// return true
if (extra == 0)
return true;
}
return false;
}
// Function for calculating minimum
// length of the subarray, which on
// removing make all elements pairwise
// distinct
function minlength(a,n)
{
// Possible range of length of subarray
let lo = 0, hi = n + 1;
let ans = 0;
// Binary search to find minimum ans
while (lo < hi)
{
let mid = Math.floor((lo + hi) / 2);
if (check(a, n, mid))
{
ans = mid;
hi = mid;
}
else
lo = mid + 1;
}
return ans;
}
// Driver Code
let a = [1, 2, 1, 2, 3 ];
let n = a.length;
document.write(minlength(a, n));
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(N * log(N)), where N is the size of the array, This is because the function "check" runs in O(n) time, and the function "minlength" performs a binary search on the length of the subarray, which takes O(log n) time.
Auxiliary Space: O(N), as it uses a hash map to store the frequencies of elements in each subarray, which can have up to n elements.
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