Find the smallest subarray having atleast one duplicate
Last Updated :
26 Dec, 2022
Given an array arr of N elements, the task is to find the length of the smallest subarray of the given array that contains at least one duplicate element. A subarray is formed from consecutive elements of an array. If no such array exists, print "-1".
Examples:
Input: arr = {1, 2, 3, 1, 5, 4, 5}
Output: 3
Explanation:

Input: arr = {4, 7, 11, 3, 1, 2, 4}
Output: 7
Explanation:

Naive Approach:
- The trick is to find all pairs of two elements with equal value. Since these two elements have equal value, the subarray enclosing them would have at least a single duplicate and will be one of the candidates for the answer.
- A simple solution is to use two nested loops to find every pair of elements.If the two elements are equal then update the maximum length obtained so far.
Below is the implementation of the above approach:
C++
// C++ program to find
// the smallest subarray having
// atleast one duplicate
#include <bits/stdc++.h>
using namespace std;
// Function to calculate
// SubArray Length
int subArrayLength(int arr[], int n)
{
int minLen = INT_MAX;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
// If the two elements are equal,
// then the subarray arr[i..j]
// will definitely have a duplicate
if (arr[i] == arr[j]) {
// Update the minimum length
// obtained so far
minLen = min(minLen, i - j + 1);
}
}
}
if (minLen == INT_MAX) {
return -1;
}
return minLen;
}
// Driver Code
int main()
{
int n = 7;
int arr[] = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
cout << ans << '\n';
return 0;
}
Java
// Java program to find
// the smallest subarray having
// atleast one duplicate
class GFG
{
final static int INT_MAX = Integer.MAX_VALUE;
// Function to calculate
// SubArray Length
static int subArrayLength(int arr[], int n)
{
int minLen = INT_MAX;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
// If the two elements are equal,
// then the subarray arr[i..j]
// will definitely have a duplicate
if (arr[i] == arr[j])
{
// Update the minimum length
// obtained so far
minLen = Math.min(minLen, i - j + 1);
}
}
}
if (minLen == INT_MAX)
{
return -1;
}
return minLen;
}
// Driver Code
public static void main(String[] args)
{
int n = 7;
int arr[] = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
System.out.println(ans);
}
}
// This code is contributed by AnkitRai01
Python
# Python program for above approach
n = 7
arr = [1, 2, 3, 1, 5, 4, 5]
minLen = n + 1
for i in range(1, n):
for j in range(0, i):
if arr[i]== arr[j]:
minLen = min(minLen, i-j + 1)
if minLen == n + 1:
print("-1")
else:
print(minLen)
C#
// C# program to find
// the smallest subarray having
// atleast one duplicate
using System;
class GFG
{
static int INT_MAX = int.MaxValue;
// Function to calculate
// SubArray Length
static int subArrayLength(int []arr, int n)
{
int minLen = INT_MAX;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < i; j++)
{
// If the two elements are equal,
// then the subarray arr[i..j]
// will definitely have a duplicate
if (arr[i] == arr[j])
{
// Update the minimum length
// obtained so far
minLen = Math.Min(minLen, i - j + 1);
}
}
}
if (minLen == INT_MAX)
{
return -1;
}
return minLen;
}
// Driver Code
public static void Main()
{
int n = 7;
int []arr = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
Console.WriteLine(ans);
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// javascript program to find
// the smallest subarray having
// atleast one duplicate
var INT_MAX = Number.MAX_VALUE;
// Function to calculate
// SubArray Length
function subArrayLength( arr , n) {
var minLen = INT_MAX;
for (var i = 1; i < n; i++) {
for (var j = 0; j < i; j++) {
// If the two elements are equal,
// then the subarray arr[i..j]
// will definitely have a duplicate
if (arr[i] == arr[j]) {
// Update the minimum length
// obtained so far
minLen = Math.min(minLen, i - j + 1);
}
}
}
if (minLen == INT_MAX) {
return -1;
}
return minLen;
}
// Driver Code
var n = 7;
var arr = [ 1, 2, 3, 1, 5, 4, 5 ];
var ans = subArrayLength(arr, n);
document.write(ans);
// This code contributed by Princi Singh
</script>
Time Complexity: O(N2)
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Efficient Approach:
This problem can be solved in O(N) time and O(N) Auxiliary space using the idea of hashing technique. The idea is to iterate through each element of the array in a linear way and for each element, find its last occurrence using a hashmap and then update the value of min length using the difference of the last occurrence and the current index. Also, update the value of the last occurrence of the element by the value of the current index.
Below is the implementation of the above approach:
C++
// C++ program to find
// the smallest subarray having
// atleast one duplicate
#include <bits/stdc++.h>
using namespace std;
// Function to calculate
// SubArray Length
int subArrayLength(int arr[], int n)
{
int minLen = INT_MAX;
// Last stores the index of the last
// occurrence of the corresponding value
unordered_map<int, int> last;
for (int i = 0; i < n; i++) {
// If the element has already occurred
if (last[arr[i]] != 0) {
minLen = min(minLen, i - last[arr[i]] + 2);
}
last[arr[i]] = i + 1;
}
if (minLen == INT_MAX) {
return -1;
}
return minLen;
}
// Driver Code
int main()
{
int n = 7;
int arr[] = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
cout << ans << '\n';
return 0;
}
Java
// Java program to find
// the smallest subarray having
// atleast one duplicate
import java.util.*;
class GFG
{
// Function to calculate
// SubArray Length
static int subArrayLength(int arr[], int n)
{
int minLen = Integer.MAX_VALUE;
// Last stores the index of the last
// occurrence of the corresponding value
HashMap<Integer, Integer> last = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
{
// If the element has already occurred
if (last.containsKey(arr[i]) && last.get(arr[i]) != 0)
{
minLen = Math.min(minLen, i - last.get(arr[i]) + 2);
}
last.put(arr[i], i + 1);
}
if (minLen == Integer.MAX_VALUE)
{
return -1;
}
return minLen;
}
// Driver Code
public static void main(String[] args)
{
int n = 7;
int arr[] = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
System.out.print(ans);
}
}
// This code is contributed by 29AjayKumar
Python
# Python program for above approach
n = 7
arr = [1, 2, 3, 1, 5, 4, 5]
last = dict()
minLen = n + 1
for i in range(0, n):
if arr[i] in last:
minLen = min(minLen, i-last[arr[i]]+2)
last[arr[i]]= i + 1
if minLen == n + 1:
print("-1")
else:
print(minLen)
C#
// C# program to find
// the smallest subarray having
// atleast one duplicate
using System;
using System.Collections.Generic;
class GFG
{
// Function to calculate
// SubArray Length
static int subArrayLength(int []arr, int n)
{
int minLen = int.MaxValue;
// Last stores the index of the last
// occurrence of the corresponding value
Dictionary<int, int> last = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
// If the element has already occurred
if (last.ContainsKey(arr[i]) && last[arr[i]] != 0)
{
minLen = Math.Min(minLen, i - last[arr[i]] + 2);
}
if(last.ContainsKey(arr[i]))
last[arr[i]] = i + 1;
else
last.Add(arr[i], i + 1);
}
if (minLen == int.MaxValue)
{
return -1;
}
return minLen;
}
// Driver Code
public static void Main(String[] args)
{
int n = 7;
int []arr = { 1, 2, 3, 1, 5, 4, 5 };
int ans = subArrayLength(arr, n);
Console.Write(ans);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program to find
// the smallest subarray having
// atleast one duplicate
// Function to calculate
// SubArray Length
function subArrayLength(arr, n)
{
let minLen = Number.MAX_VALUE;
// Last stores the index of the last
// occurrence of the corresponding value
let last = new Map();
for (let i = 0; i < n; i++)
{
// If the element has already occurred
if (last.has(arr[i]) && last.get(arr[i]) != 0)
{
minLen =
Math.min(minLen, i - last.get(arr[i]) + 2);
}
last.set(arr[i], i + 1);
}
if (minLen == Number.MAX_VALUE)
{
return -1;
}
return minLen;
}
// Driver code
let n = 7;
let arr = [ 1, 2, 3, 1, 5, 4, 5 ];
let ans = subArrayLength(arr, n);
document.write(ans);
</script>
Time Complexity: O(N), where N is size of array
Auxiliary Space: O(N) because it is using unordered_map last
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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