Count of possible subarrays and subsequences using given length of Array
Last Updated :
18 Nov, 2021
Given an integer N which denotes the length of an array, the task is to count the number of subarray and subsequence possible with the given length of the array.
Examples:
Input: N = 5
Output:
Count of subarray = 15
Count of subsequence = 32
Input: N = 3
Output:
Count of subarray = 6
Count of subsequence = 8
Approach: The key observation fact for the count of the subarray is the number of ends position possible for each index elements of the array can be (N – i), Therefore the count of the subarray for an array of size N can be:
Count of Sub-arrays = (N) * (N + 1)
---------------
2
The key observation fact for the count of the subsequence possible is each element of the array can be included in a subsequence or not. Therefore, the choice for each element is 2.
Count of subsequences = 2N
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubarray( int n){
return ((n)*(n + 1))/2;
}
int countSubsequence( int n){
return pow (2, n);
}
int main()
{
int n = 5;
cout << (countSubarray(n)) << endl;
cout << (countSubsequence(n)) << endl;
return 0;
}
|
Java
class GFG{
static int countSubarray( int n){
return ((n)*(n + 1 ))/ 2 ;
}
static int countSubsequence( int n){
return ( int ) Math.pow( 2 , n);
}
public static void main(String[] args)
{
int n = 5 ;
System.out.print((countSubarray(n)) + "\n" );
System.out.print((countSubsequence(n)) + "\n" );
}
}
|
Python
def countSubarray(n):
return ((n) * (n + 1 )) / / 2
def countSubsequence(n):
return ( 2 * * n)
if __name__ = = "__main__" :
n = 5
print (countSubarray(n))
print (countSubsequence(n))
|
C#
using System;
class GFG{
static int countSubarray( int n){
return ((n)*(n + 1))/2;
}
static int countSubsequence( int n){
return ( int ) Math.Pow(2, n);
}
public static void Main(String[] args)
{
int n = 5;
Console.Write((countSubarray(n)) + "\n" );
Console.Write((countSubsequence(n)) + "\n" );
}
}
|
Javascript
<script>
function countSubarray(n){
return ((n)*(n + 1))/2;
}
function countSubsequence(n){
return Math.pow(2, n);
}
let n = 5;
document.write((countSubarray(n)) + "<br/>" );
document.write((countSubsequence(n)) + "\n" );
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...