Length of the longest subsequence consisting of distinct elements

Given an array arr[] of size N, the task is to find the length of the longest subsequence consisting of distinct elements only.

Examples: 

Input: arr[] = {1, 1, 2, 2, 2, 3, 3} 
Output:
Explanation: 
The longest subsequence with distinct elements is {1, 2, 3} 
Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 } 
Output:

 Naive Approach: The simplest approach is to generate all the subsequences of the array and check if it consists of only distinct elements or not. Keep updating the maximum length of such subsequences obtained. Finally, print the maximum length obtained.

Time Complexity: O(2N
Auxiliary Space: O(1) 



Efficient Approach: The length of the longest subsequence containing only distinct elements will be equal to the count of distinct elements in the array. Follow the steps below to solve the problem: 

  1. Traverse the given array keep inserting encountered elements in a Hashset.
  2. Since HashSet consists of only unique elements, print the size of the HashSet as the required answer after completing the traversal of the array.

Below is the implementation of the above approach: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find length of
// the longest subsequence
// consisting of distinct elements
int longestSubseq(int arr[], int n)
{
    // Stores the distinct
    // array elements
    unordered_set<int> s;
 
    // Traverse the input array
    for (int i = 0; i < n; i++) {
 
        // If current element has not
        // occurred previously
        if (s.find(arr[i]) == s.end()) {
 
            // Insert it into set
            s.insert(arr[i]);
        }
    }
 
    return s.size();
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << longestSubseq(arr, n);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to find length of
// the longest subsequence
// consisting of distinct elements
static int longestSubseq(int arr[], int n)
{
    // Stores the distinct
    // array elements
    Set<Integer> s = new HashSet<>();
   
    // Traverse the input array
    for(int i = 0; i < n; i++)
    {
   
        // If current element has not
        // occurred previously
        if (!s.contains(arr[i]))
        {
   
            // Insert it into set
            s.add(arr[i]);
        }
    }
    return s.size();
}
 
// Driver code
public static void main (String[] args)
{
     
    // Given array
    int arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 };
    int n = arr.length;
     
    // Function call
    System.out.println(longestSubseq(arr, n));    
}
}
 
// This code is contributed by offbeat
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for
# the above approach
 
# Function to find length of
# the longest subsequence
# consisting of distinct elements
def longestSubseq(arr, n):
 
    # Stores the distinct
    # array elements
    s = set()
 
    # Traverse the input array
    for i in range(n):
       
        # If current element has not
        # occurred previously
        if (arr[i] not in s):
 
            # Insert it into set
            s.add(arr[i])
 
    return len(s)
 
# Given array
arr = [1, 2, 3, 3,
       4, 5, 5, 5]
n = len(arr)
 
# Function Call
print(longestSubseq(arr, n))
 
# This code is contributed by divyeshrabadiya07
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
      
// Function to find length of
// the longest subsequence
// consisting of distinct elements
static int longestSubseq(int []arr, int n)
{
     
    // Stores the distinct
    // array elements
    HashSet<int> s = new HashSet<int>();
    
    // Traverse the input array
    for(int i = 0; i < n; i++)
    {
         
        // If current element has not
        // occurred previously
        if (!s.Contains(arr[i]))
        {
             
            // Insert it into set
            s.Add(arr[i]);
        }
    }
    return s.Count;
}
  
// Driver code
public static void Main(string[] args)
{
     
    // Given array
    int []arr = { 1, 2, 3, 3, 4, 5, 5, 5 };
    int n = arr.Length;
      
    // Function call
    Console.Write(longestSubseq(arr, n));    
}
}
 
// This code is contributed by rutvik_56
chevron_right

Output: 
5




 

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

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.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :