Longest Subarray consisting of unique elements from an Array
Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3}
Output: 5
Explanation: One possible subarray is {1, 2, 3, 4, 5}.
Input: arr[]={1, 2, 4, 4, 5, 6, 7, 8, 3, 4, 5, 3, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4}
Output: 8
Explanation: Only possible subarray is {3, 4, 5, 6, 7, 8, 1, 2}.
Naive Approach: The simplest approach to solve the problem is to generate all subarrays from the given array and check if it contains any duplicates or not to use HashSet. Find the longest subarray satisfying the condition.
Time Complexity: O(N3logN)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized by HashMap. Follow the steps below to solve the problem:
- Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and j
- Traverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap.
- After updating j, update ans accordingly to store the maximum length of the desired subarray.
- Print ans, after traversal, is completed.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int largest_subarray( int a[], int n)
{
unordered_map< int , int > index;
int ans = 0;
for ( int i = 0, j = 0; i < n; i++) {
j = max(index[a[i]], j);
ans = max(ans, i - j + 1);
index[a[i]] = i + 1;
}
return ans;
}
int32_t main()
{
int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << largest_subarray(arr, n);
}
|
Java
import java.util.*;
class GFG{
static int largest_subarray( int a[], int n)
{
HashMap<Integer,
Integer> index = new HashMap<Integer,
Integer>();
int ans = 0 ;
for ( int i = 0 , j = 0 ; i < n; i++)
{
j = Math.max(index.containsKey(a[i]) ?
index.get(a[i]) : 0 , j);
ans = Math.max(ans, i - j + 1 );
index.put(a[i], i + 1 );
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 };
int n = arr.length;
System.out.print(largest_subarray(arr, n));
}
}
|
Python3
from collections import defaultdict
def largest_subarray(a, n):
index = defaultdict( lambda : 0 )
ans = 0
j = 0
for i in range (n):
j = max (index[a[i]], j)
ans = max (ans, i - j + 1 )
index[a[i]] = i + 1
i + = 1
return ans
arr = [ 1 , 2 , 3 , 4 , 5 , 1 , 2 , 3 ]
n = len (arr)
print (largest_subarray(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int largest_subarray( int []a, int n)
{
Dictionary< int ,
int > index = new Dictionary< int ,
int >();
int ans = 0;
for ( int i = 0, j = 0; i < n; i++)
{
j = Math.Max(index.ContainsKey(a[i]) ?
index[a[i]] : 0, j);
ans = Math.Max(ans, i - j + 1);
if (index.ContainsKey(a[i]))
index[a[i]] = i + 1;
else
index.Add(a[i], i + 1);
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 4, 5, 1, 2, 3 };
int n = arr.Length;
Console.Write(largest_subarray(arr, n));
}
}
|
Javascript
<script>
function largest_subarray(a, n)
{
let index = new Map();
let ans = 0;
for (let i = 0, j = 0; i < n; i++)
{
j = Math.max(index.has(a[i]) ?
index.get(a[i]) : 0, j);
ans = Math.max(ans, i - j + 1);
index.set(a[i], i + 1);
}
return ans;
}
let arr = [ 1, 2, 3, 4, 5, 1, 2, 3 ];
let n = arr.length;
document.write(largest_subarray(arr, n));
</script>
|
Time Complexity: O(N) in best case and O(n^2) in worst case.
NOTE: We can make Time complexity equal to O(n * logn) by using balanced binary tree structures (`std::map` in c++ and `TreeMap` in Java.) instead of Hash structures.
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Last Updated :
11 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...