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:
- Initialize a Map to store the frequency of each distinct array element.
- Traverse the array and update frequency of each element in the Map.
- Finally, traverse the Map and print the sum of frequency of each distinct array element.
Below is the implementation of the above approach:
C++
// 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); } |
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.

