VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subarray-consisting-of-unique-elements-from-an-array/

⇱ Longest Subarray consisting of unique elements from an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray consisting of unique elements from an Array

Last Updated : 15 Jul, 2025

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:
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:


Output: 
5

 

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

Comment