Given an integer array, count the total number of strictly increasing subarrays in it.

For example,

Input:  A[] = { 1, 2, 4, 4, 5}
 
Output: The total number of strictly increasing subarrays is 4
 
{ 1, 2 }, { 1, 2, 4 }, { 2, 4 }, { 4, 5 }
 
 
Input:  A[] = { 1, 3, 2 }
 
Output: The total number of strictly increasing subarrays is 1
 
{1, 3}
 
 
Input:  A[] = { 5, 4, 3, 2, 1 }
 
Output: The total number of strictly increasing subarrays is 0

Practice this problem

Please note that the problem specifically targets subarrays that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements. A strictly increasing subarray has a size of at least 2.

 
A naive solution would be to generate all possible subarrays and check if each subarray is strictly increasing or not. The time complexity of this approach is O(n3) since there are n2 subarrays in an array of size n, and time spent on each subarray would be O(n).

We can optimize the time complexity of this approach to O(n2) by using the fact that if subarray arr[i, j-1] is strictly increasing, then subarray arr[i, j] would be strictly increasing if arr[j-1] < arr[j]. And if arr[j-1] >= arr[j], then subarray arr[i, j] would be not strictly increasing and the same can be said for subarrays arr[i, j+1], arr[i, j+2], … , all the way till arr[i, n-1]. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of strictly increasing subarrays is 4

Java


Download  Run Code

Output:

The total number of strictly increasing subarrays is 4

Python


Download  Run Code

Output:

The total number of strictly increasing subarrays is 4

We can improve the time complexity to O(n) by keeping track of the length of the current strictly increasing subarray and increment the final count by len–1 whenever the current subarray length len is increased by 1. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The total number of strictly increasing subarrays is 6

Java


Download  Run Code

Output:

The total number of strictly increasing subarrays is 6

Python


Download  Run Code

Output:

The total number of strictly increasing subarrays is 6