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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count of subsequences of length atmost K containing distinct prime elements
Next article icon

Count of subsequences consisting of the same element

Last Updated : 21 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] consisting of N integers, the task is to find the total number of subsequence which contain only one distinct number repeated throughout the subsequence.

Examples:  

Input: A[] = {1, 2, 1, 5, 2} 
Output: 7 
Explanation: 
Subsequences {1}, {2}, {1}, {5}, {2}, {1, 1} and {2, 2} satisfy the required conditions.

Input: A[] = {5, 4, 4, 5, 10, 4} 
Output: 11 
Explanation: 
Subsequences {5}, {4}, {4}, {5}, {10}, {4}, {5, 5}, {4, 4}, {4, 4}, {4, 4} and {4, 4, 4} satisfy the required conditions. 

Approach: 
Follow the steps below to solve the problem: 

  • Iterate over the array and calculate the frequency of each element in a HashMap.
  • Traverse the HashMap. For each element, calculate the number of desired subsequences possible by the equation:

 Number of subsequences possible by arr[i] = 2freq[arr[i]] – 1 

  • Calculate the total possible subsequences from the given array. 
     

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count subsequences in
// array containing same element
void CountSubSequence(int A[], int N)
{
    // Stores the count
    // of subsequences
    int result = 0;
 
    // Stores the frequency
    // of array elements
    map<int, int> mp;
 
    for (int i = 0; i < N; i++) {
 
        // Update frequency of A[i]
        mp[A[i]]++;
    }
 
    for (auto it : mp) {
 
        // Calculate number of subsequences
        result
            = result + pow(2, it.second) - 1;
    }
 
    // Print the result
    cout << result << endl;
}
 
// Driver code
int main()
{
    int A[] = { 5, 4, 4, 5, 10, 4 };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    CountSubSequence(A, N);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to count subsequences in
// array containing same element
static void CountSubSequence(int A[], int N)
{
     
    // Stores the count
    // of subsequences
    int result = 0;
 
    // Stores the frequency
    // of array elements
    Map<Integer,
        Integer> mp = new HashMap<Integer,
                                  Integer>();
 
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of A[i]
        mp.put(A[i], mp.getOrDefault(A[i], 0) + 1);
    }
 
    for(Integer it : mp.values())
    {
         
        // Calculate number of subsequences
        result = result + (int)Math.pow(2, it) - 1;
    }
     
    // Print the result
    System.out.println(result);
}
 
// Driver code
public static void main(String[] args)
{
    int A[] = { 5, 4, 4, 5, 10, 4 };
    int N = A.length;
     
    CountSubSequence(A, N);
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program to implement 
# the above approach 
 
# Function to count subsequences in 
# array containing same element 
def CountSubSequence(A, N):
     
    # Stores the frequency 
    # of array elements 
    mp = {}
     
    for element in A:
        if element in mp:
            mp[element] += 1
        else:
            mp[element] = 1
             
    result = 0
     
    for key, value in mp.items():
         
        # Calculate number of subsequences 
        result += pow(2, value) - 1
         
    # Print the result     
    print(result)
 
# Driver code
A = [ 5, 4, 4, 5, 10, 4 ]
N = len(A)
 
CountSubSequence(A, N)
 
# This code is contributed by jojo9911
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count subsequences in
// array containing same element
public static void CountSubSequence(int []A, int N)
{
     
    // Stores the count
    // of subsequences
    int result = 0;
 
    // Stores the frequency
    // of array elements
    var mp = new Dictionary<int, int>();
 
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of A[i]
        if(mp.ContainsKey(A[i]))
            mp[A[i]] += 1;
        else
            mp.Add(A[i], 1);
    }
 
    foreach(var it in mp)
    {
         
        // Calculate number of subsequences
        result = result +
                 (int)Math.Pow(2, it.Value) - 1;
    }
     
    // Print the result
    Console.Write(result);
}
 
// Driver code
public static void Main()
{
    int []A = { 5, 4, 4, 5, 10, 4 };
    int N = A.Length;
     
    CountSubSequence(A, N);
}
}
 
// This code is contributed by grand_master
 
 

Javascript




<script>
 
// Javascript program to implement
// the above approach
 
// Function to count subsequences in
// array containing same element
function CountSubSequence(A, N)
{
    // Stores the count
    // of subsequences
    var result = 0;
 
    // Stores the frequency
    // of array elements
    var mp = new Map(); 
 
    for (var i = 0; i < N; i++) {
 
        // Update frequency of A[i]
        if(mp.has(A[i]))
            mp.set(A[i], mp.get(A[i])+1)
        else
            mp.set(A[i], 1)
    }
 
    mp.forEach((value, key) => {
         
 
        // Calculate number of subsequences
        result
            = result + Math.pow(2, value) - 1;
    });
 
    // Print the result
    document.write( result );
}
 
// Driver code
var A = [5, 4, 4, 5, 10, 4];
var N = A.length;
CountSubSequence(A, N);
 
// This code is contributed by itsok.
</script>
 
 
Output: 
11

 

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



Next Article
Count of subsequences of length atmost K containing distinct prime elements

D

divyeshrabadiya07
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • cpp-map
  • frequency-counting
  • subsequence
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

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
  • 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
  • Count of subsequences which consists exactly K prime numbers
    Given an integer K and an array arr[], the task is to find the number of subsequences from the given array such that each subsequence consists exactly K prime numbers.Example: Input: K = 2, arr = [2, 3, 4, 6] Output: 4 Explanation: There are 4 subsequences which consists exactly 2 prime numbers {2,
    7 min read
  • Count of subsequences of length atmost K containing distinct prime elements
    Given an array arr of length N and an integer K, the task is to count the number of possible subsequences of length at most K which contains distinct prime elements from the array. Examples: Input: arr[] = {1, 2, 2, 3, 3, 4, 5}, N = 7, K = 3 Output: 18 Explanation: {}, {2}, {2}, {3}, {3}, {5}, {2, 3
    12 min read
  • Count number of increasing subsequences of size k
    Given an array arr[] containing n integers. The problem is to count number of increasing subsequences in the array of size k. Examples: Input : arr[] = {2, 6, 4, 5, 7}, k = 3Output : 5The subsequences of size '3' are:{2, 6, 7}, {2, 4, 5}, {2, 4, 7},{2, 5, 7} and {4, 5, 7}.Input : arr[] = {12, 8, 11,
    15+ min read
  • Count of sub-sequences which satisfy the given condition
    Given a string str consisting of digits, the task is to find the number of possible 4 digit sub-sequences which are of the form (x, x, x + 1, x + 1) where x can be from the range [0, 8]. Examples: Input: str = "1122" Output: 1 Only one sub-sequence is valid, i.e the entire string itself. Input: str
    10 min read
  • Count of subsequences having maximum distinct elements
    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
    5 min read
  • Count subsequence of length three in a given string
    Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string. Examples : Input : string = "GFGFGYSYIOIWIN", subsequence = "GFG" Output : 4 Explanation : There are 4 such subsequences as shown: GFGFGYSYIOIWIN GFGFGYSYIOIWIN GFGFGYSYI
    15 min read
  • Find the number of subsequences of N friends
    Given two arrays A[] and B[] of length N and M respectively. A[] represents the age of N friends and B[] contains M number of pairs in the form of (X → Y), which denotes X knows Y and vice-versa. Then your task is to output the count of all possible sequences of length N friends with the given condi
    15 min read
  • Count subsequences with same values of Bitwise AND, OR and XOR
    We are given an array arr of n element. We need to count number of non-empty subsequences such that these individual subsequences have same values of bitwise AND, OR and XOR. For example, we need to count a subsequence (x, y, z) if (x | y | z) is equal to (x & y & z) and (x ^ y ^ z). For a s
    6 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