Length of the longest subsequence consisting of distinct elements
Last Updated :
04 Jan, 2023
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: 3
Explanation:
The longest subsequence with distinct elements is {1, 2, 3}
Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
Output: 5
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:
- Traverse the given array keep inserting encountered elements in a Hashset.
- 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++
#include <bits/stdc++.h>
using namespace std;
int longestSubseq( int arr[], int n)
{
unordered_set< int > s;
for ( int i = 0; i < n; i++) {
if (s.find(arr[i]) == s.end()) {
s.insert(arr[i]);
}
}
return s.size();
}
int main()
{
int arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << longestSubseq(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int longestSubseq( int arr[], int n)
{
Set<Integer> s = new HashSet<>();
for ( int i = 0 ; i < n; i++)
{
if (!s.contains(arr[i]))
{
s.add(arr[i]);
}
}
return s.size();
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 3 , 3 , 4 , 5 , 5 , 5 };
int n = arr.length;
System.out.println(longestSubseq(arr, n));
}
}
|
Python3
def longestSubseq(arr, n):
s = set ()
for i in range (n):
if (arr[i] not in s):
s.add(arr[i])
return len (s)
arr = [ 1 , 2 , 3 , 3 ,
4 , 5 , 5 , 5 ]
n = len (arr)
print (longestSubseq(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int longestSubseq( int []arr, int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
if (!s.Contains(arr[i]))
{
s.Add(arr[i]);
}
}
return s.Count;
}
public static void Main( string [] args)
{
int []arr = { 1, 2, 3, 3, 4, 5, 5, 5 };
int n = arr.Length;
Console.Write(longestSubseq(arr, n));
}
}
|
Javascript
<script>
function longestSubseq(arr, n)
{
var s = new Set();
for ( var i = 0; i < n; i++) {
if (s.has(arr[i]) == false ) {
s.add(arr[i]);
}
}
return s.size;
}
var arr = [ 1, 2, 3, 3, 4, 5, 5, 5 ];
var n = arr.length;
document.write(longestSubseq(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...