Sunday, November 17, 2024
Google search engine
HomeData Modelling & AILength of the longest subsequence consisting of distinct elements

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: 

C++




// 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;
}


Java




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


Python3




# 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


C#




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


Javascript




<script>
  
// Javascript program for the above approach
// Function to find length of
// the longest subsequence
// consisting of distinct elements
function longestSubseq(arr, n)
{
    // Stores the distinct
    // array elements
    var s = new Set();
  
    // Traverse the input array
    for (var i = 0; i < n; i++) {
  
        // If current element has not
        // occurred previously
        if (s.has(arr[i]) == false) {
  
            // Insert it into set
            s.add(arr[i]);
        }
    }
  
    return s.size;
}
  
// Driver Code
  
// Given array
var arr = [ 1, 2, 3, 3, 4, 5, 5, 5 ];
var n = arr.length;
 
// Function Call
document.write(longestSubseq(arr, n));
 
// This code is contributed by ShubhamSingh10
</script>


Output: 

5

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments