The Wayback Machine - https://web.archive.org/web/20210130001234/https://www.geeksforgeeks.org/count-subarrays-having-a-single-distinct-element-that-can-be-obtained-from-a-given-array/
Skip to content
Related Articles

Related Articles

Count subsequences having a single distinct element that can be obtained from a given array
  • Last Updated : 25 Jan, 2021

Given an array arr[] of size N, the task is to count the number of distinct subsequences consisting of a single distinct element that can be obtained from a given array.

Examples:

Input: N = 4, arr[] = { 2, 2, 2, 2 }
Output: 4
Explanation: All such subsequences are {{2}, {2, 2}, {2, 2, 2}, {2, 2, 2, 2}}. Therefore, total count of such subarrays are 4.

Input: N = 3, arr[] = { 1, 1, 3 }
Output: 3

Approach: The idea is to count the frequency of each distinct array element and make subsequences by either taking one array element or two array elements and so on. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++

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 count subarrays of
// single distinct element into
// which given array can be split
void divisionalArrays(int arr[3], int N)
{
    // Stores the count
    int sum = 0;
  
    // Stores frequency of
    // array elements
    unordered_map<int, int> mp;
  
    // Traverse the array
    for (int i = 0; i < N; i++) {
        mp[arr[i]]++;
    }
  
    // Traverse the map
    for (auto x : mp) {
          
  
        // Increase count of
        // subarrays by (frequency)
       sum += x.second;
    }
    cout << sum << endl;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 1, 3 };
    int N = sizeof(arr)
            / sizeof(arr[0]);
    divisionalArrays(arr, N);
}

chevron_right


Output:

3

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :