Skip to content
Related Articles

Related Articles

Improve Article

Longest Subarray consisting of unique elements from an Array

  • Difficulty Level : Medium
  • Last Updated : 13 Sep, 2021

Given an array arr[] consisting of N integers, the task is to find the largest subarray consisting of unique elements only.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, 2, 3, 4, 5, 1, 2, 3} 
Output:
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:
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:

  1. Initialize a variable j, to store the maximum value of the index such that there are no repeated elements between index i and j
  2. Traverse the array and keep updating j based on the previous occurrence of a[i] stored in the HashMap.
  3. After updating j, update ans accordingly to store the maximum length of the desired subarray.
  4. Print ans, after traversal, is completed.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find largest
// subarray with no duplicates
int largest_subarray(int a[], int n)
{
    // Stores index of array elements
    unordered_map<int, int> index;
    int ans = 0;
    for (int i = 0, j = 0; i < n; i++) {
  
        // Update j based on previous
        // occurrence of a[i]
        j = max(index[a[i]], j);
  
        // Update ans to store maximum
        // length of subarray
        ans = max(ans, i - j + 1);
  
        // Store the index of current
        // occurrence of a[i]
        index[a[i]] = i + 1;
    }
  
    // Return final ans
    return ans;
}
  
// Driver Code
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




// Java program to implement
// the above approach
import java.util.*;
class GFG{
  
// Function to find largest
// subarray with no duplicates
static int largest_subarray(int a[], int n)
{
    // Stores index of array elements
    HashMap<Integer,
            Integer> index = new HashMap<Integer,
                                         Integer>();
    int ans = 0;
    for(int i = 0, j = 0; i < n; i++)
    {
  
        // Update j based on previous
        // occurrence of a[i]
        j = Math.max(index.containsKey(a[i]) ? 
                             index.get(a[i]) : 0, j);
  
        // Update ans to store maximum
        // length of subarray
        ans = Math.max(ans, i - j + 1);
  
        // Store the index of current
        // occurrence of a[i]
        index.put(a[i], i + 1);
    }
  
    // Return final ans
    return ans;
}
  
// Driver Code
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));
}
}
  
// This code is contributed by Rajput-Ji

Python3




# Python3 program to implement
# the above approach
from collections import defaultdict
  
# Function to find largest
# subarray with no duplicates
def largest_subarray(a, n):
  
    # Stores index of array elements
    index = defaultdict(lambda : 0)
      
    ans = 0
    j = 0
  
    for i in range(n):
  
        # Update j based on previous
        # occurrence of a[i]
        j = max(index[a[i]], j)
  
        # Update ans to store maximum
        # length of subarray
        ans = max(ans, i - j + 1)
  
        # Store the index of current
        # occurrence of a[i]
        index[a[i]] = i + 1
  
        i += 1
  
    # Return final ans 
    return ans
  
# Driver Code
arr = [ 1, 2, 3, 4, 5, 1, 2, 3 ]
n = len(arr)
  
# Function call
print(largest_subarray(arr, n))
  
# This code is contributed by Shivam Singh

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find largest
// subarray with no duplicates
static int largest_subarray(int []a, int n)
{
      
    // Stores index of array elements
    Dictionary<int,
               int> index = new Dictionary<int,
                                           int>();
    int ans = 0;
    for(int i = 0, j = 0; i < n; i++)
    {
  
        // Update j based on previous
        // occurrence of a[i]
        j = Math.Max(index.ContainsKey(a[i]) ? 
                                 index[a[i]] : 0, j);
  
        // Update ans to store maximum
        // length of subarray
        ans = Math.Max(ans, i - j + 1);
  
        // Store the index of current
        // occurrence of a[i]
        if(index.ContainsKey(a[i]))
            index[a[i]] = i + 1;
        else
            index.Add(a[i], i + 1);
    }
  
    // Return readonly ans
    return ans;
}
  
// Driver Code
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));
}
}
  
// This code is contributed by Amit Katiyar

Javascript




<script>
  
// Javascript program to implement
// the above approach
  
// Function to find largest
// subarray with no duplicates
function largest_subarray(a, n)
{
    // Stores index of array elements
    let index = new Map();
    let ans = 0;
    for(let i = 0, j = 0; i < n; i++)
    {
   
        // Update j based on previous
        // occurrence of a[i]
        j = Math.max(index.has(a[i]) ?
                             index.get(a[i]) : 0, j);
   
        // Update ans to store maximum
        // length of subarray
        ans = Math.max(ans, i - j + 1);
   
        // Store the index of current
        // occurrence of a[i]
        index.set(a[i], i + 1);
    }
   
    // Return final ans
    return ans;
}
  
// Driver code
  
    let arr = [ 1, 2, 3, 4, 5, 1, 2, 3 ];
    let n = arr.length;
    document.write(largest_subarray(arr, n));
  
</script>
Output: 
5

 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :