Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize count of distinct elements in a subsequence of size K in given array
Next article icon

Count of subsequences having maximum distinct elements

Last Updated : 28 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an arr of size n. The problem is to count all the subsequences having maximum number of distinct elements.

Examples: 

Input : arr[] = {4, 7, 6, 7} Output : 2 The indexes for the subsequences are: {0, 1, 2} - Subsequence is {4, 7, 6} and {0, 2, 3} - Subsequence is {4, 6, 7}  Input : arr[] = {9, 6, 4, 4, 5, 9, 6, 1, 2} Output : 8

Naive Approach: Consider all the subsequences having distinct elements and count the one’s having maximum distinct elements.

Efficient Approach: Create a hash table to store the frequency of each element of the array. Take product of all the frequencies. 
The solution is based on the fact that there is always 1 subsequence possible when all elements are distinct. If elements repeat, every occurrence of repeating element makes a mew subsequence of distinct elements.

Implementation:

C++




// C++ implementation to count subsequences having
// maximum distinct elements
#include <bits/stdc++.h>
using namespace std;
 
typedef unsigned long long int ull;
 
// function to count subsequences having
// maximum distinct elements
ull countSubseq(int arr[], int n)
{
    // unordered_map 'um' implemented as
    // hash table
    unordered_map<int, int> um;
 
    ull count = 1;
 
    // count frequency of each element
    for (int i = 0; i < n; i++)
        um[arr[i]]++;
 
    // traverse 'um'
    for (auto itr = um.begin(); itr != um.end(); itr++)
 
        // multiply frequency of each element
        // and accumulate it in 'count'
        count *= (itr->second);
 
    // required number of subsequences
    return count;
}
 
// Driver program to test above
int main()
{
    int arr[] = { 4, 7, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Count = "
         << countSubseq(arr, n);
    return 0;
}
 
 

Java




// Java implementation to count subsequences having
// maximum distinct elements
import java.util.HashMap;
 
class geeks
{
     
    // function to count subsequences having
    // maximum distinct elements
    public static long countSubseq(int[] arr, int n)
    {
 
        // unordered_map 'um' implemented as
        // hash table
        HashMap<Integer, Integer> um = new HashMap<>();
 
        long count = 1;
 
        // count frequency of each element
        for (int i = 0; i < n; i++)
        {
            if (um.get(arr[i]) != null)
            {
                int a = um.get(arr[i]);
                um.put(arr[i], ++a);
            }
            else
                um.put(arr[i], 1);
        }
         
        // traverse 'um'
        for (HashMap.Entry<Integer, Integer> entry : um.entrySet())
        {
             
            // multiply frequency of each element
            // and accumulate it in 'count'
            count *= entry.getValue();
        }
         
        // required number of subsequences
        return count;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 4, 7, 6, 7 };
        int n = arr.length;
        System.out.println("Count = " + countSubseq(arr, n));
    }
}
 
// This code is contributed by
// sanjeev2552
 
 

Python3




# Python 3 implementation to count subsequences
# having maximum distinct elements
 
# function to count subsequences having
# maximum distinct elements
def countSubseq(arr, n):
     
    # unordered_map 'um' implemented
    # as hash table
    # take range equal to maximum
    # value of arr
    um = {i:0 for i in range(8)}
 
    count = 1
 
    # count frequency of each element
    for i in range(n):
        um[arr[i]] += 1
 
    # traverse 'um'
    for key, values in um.items():
         
        # multiply frequency of each element
        # and accumulate it in 'count'
        if(values > 0):
            count *= values
 
    # required number of subsequences
    return count
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 7, 6, 7]
    n = len(arr)
    print("Count =", countSubseq(arr, n))
 
# This code is contributed by
# Surendra_Gangwar
 
 

C#




// C# implementation to count subsequences
// having maximum distinct elements
using System;
using System.Collections.Generic;
     
class GFG
{
     
    // function to count subsequences having
    // maximum distinct elements
    public static long countSubseq(int[] arr,
                                   int n)
    {
 
        // unordered_map 'um' implemented as
        // hash table
        Dictionary<int,
                   int> um = new Dictionary<int,
                                            int>();
 
        long count = 1;
 
        // count frequency of each element
        for (int i = 0; i < n; i++)
        {
            if (um.ContainsKey(arr[i]))
            {
                int a = um[arr[i]];
                um.Remove(arr[i]);
                um.Add(arr[i], ++a);
            }
            else
                um.Add(arr[i], 1);
        }
         
        // traverse 'um'
        foreach(KeyValuePair<int, int> entry in um)
        {
             
            // multiply frequency of each element
            // and accumulate it in 'count'
            count *= entry.Value;
        }
         
        // required number of subsequences
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 4, 7, 6, 7 };
        int n = arr.Length;
        Console.WriteLine("Count = " +
                           countSubseq(arr, n));
    }
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
// Javascript implementation to count subsequences having
// maximum distinct elements
 
// function to count subsequences having
// maximum distinct elements
function countSubseq(arr, n)
{
 
    // unordered_map 'um' implemented as
    // hash table
    var um = new Map();
 
    var count = 1;
 
    // count frequency of each element
    for (var i = 0; i < n; i++)
    {
        if(um.has(arr[i]))
            um.set(arr[i], um.get(arr[i])+1)
        else
            um.set(arr[i], 1);
    }
 
    // traverse 'um'
    um.forEach((value, key) => {
         
        // multiply frequency of each element
        // and accumulate it in 'count'
        count *= value;
    });
     
    // required number of subsequences
    return count;
}
 
// Driver program to test above
var arr = [4, 7, 6, 7];
var n = arr.length;
document.write( "Count = "
      + countSubseq(arr, n));
 
// This code is contributed by noob2000.
</script>
 
 

Output: 

Count = 2

Time Complexity: O(n). 
Auxiliary Space: O(n).



Next Article
Maximize count of distinct elements in a subsequence of size K in given array

A

ayushjauhari14
Improve
Article Tags :
  • Arrays
  • Combinatorial
  • DSA
  • subsequence
Practice Tags :
  • Arrays
  • Combinatorial

Similar Reads

  • Count of Subsequences with distinct elements
    Given an array arr[] (1<=a[i]<=1e9) containing N (1<=N<=1e5) elements, the task is to find the total number of subsequences such that all elements in that subsequences are distinct. Since the answer can be very large print and modulo 1e9+7. Examples: Input: arr[] = [1, 1, 2, 2]Output: 8E
    5 min read
  • Maximize count of distinct elements in a subsequence of size K in given array
    Given an array arr[] of N integers and an integer K, the task is to find the maximum count of distinct elements over all the subsequences of K integers. Example: Input: arr[]={1, 1, 2, 2}, K=3Output: 2Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are
    4 min read
  • Count subsets having distinct even numbers
    Given a sequence of n numbers. The task is to count all the subsets of the given set which only have even numbers and all are distinct. Note: By the property of sets, if two subsets have the same set of elements then they are considered as one. For example: [2, 4, 8] and [4, 2, 8] are considered to
    5 min read
  • Maximum sum subsequence with at-least k distant elements
    Given an array and a number k, find a subsequence such that Sum of elements in subsequence is maximumIndices of elements of subsequence differ atleast by k Examples Input : arr[] = {4, 5, 8, 7, 5, 4, 3, 4, 6, 5} k = 2 Output: 19 Explanation: The highest value is obtained if you pick indices 1, 4, 7,
    6 min read
  • 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: 3 Explanation: The longest subsequence with distinct elements is {1, 2, 3} Input: arr[] = { 1, 2, 3, 3, 4, 5, 5, 5 }
    4 min read
  • Maximum sum of subarrays having distinct elements of length K
    Given an array, arr[] and a value k, represent the length of the subarray to be considered. Find the maximum sum that can be obtained from the subarray of length k such that each element of the subarray is unique. If there is no subarray that meets the required condition then return 0. Examples: Inp
    13 min read
  • Length of longest subsequence consisting of distinct adjacent elements
    Given an array arr[], the task is to find the length of the longest subsequence of the array arr[] such that all adjacent elements in the subsequence are different. Examples: Input: arr[] = {4, 2, 3, 4, 3}Output: 5Explanation:The longest subsequence where no two adjacent elements are equal is {4, 2,
    5 min read
  • Count Distinct Elements In Every Window of Size K
    Given an array arr[] of size n and an integer k, return the count of distinct numbers in all windows of size k. Examples: Input: arr[] = [1, 2, 1, 3, 4, 2, 3], k = 4Output: [3, 4, 4, 3]Explanation: First window is [1, 2, 1, 3], count of distinct numbers is 3. Second window is [2, 1, 3, 4] count of d
    10 min read
  • Count subsequences having average of its elements equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to count the number of subsequences of the given array with average K. Examples: Input: arr[] = {9, 7, 8, 9}, K = 8Output: 5Explanation: The subsequences having average 8 are {8}, {9, 7}, {7, 9}, {9, 7, 8}, {7, 8, 9}. Input:
    12 min read
  • Count Distinct Subsequences
    Given a string str of length n, your task is to find the count of distinct subsequences of it. Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
    14 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences