Count number of strictly increasing and decreasing subarrays
Last Updated :
11 Feb, 2025
Given an array arr[] of size N, the task is to find the number of strictly increasing and decreasing subarrays.
Examples:
Input: arr[] = { 80, 50, 60, 70, 40, 40 }
Output: 9 8
Explanation: The increasing subarrays are: {80}, {50}, {60}, {70}, {40}, {40}, {50, 60}, {60, 70} and {50, 60, 70}. The decreasing subarrays are: {80}, {50}, {60}, {70}, {40}, {40}, {80, 50} and {70, 40}.
Input: arr[] = { 10, 20, 23, 12, 5, 4, 61, 67, 87, 9 }
Output: 2 2
Approach: To solve the problem, follow the below idea:
The problem can be solved in two parts: count the number of strictly increasing subarrays and count the number of strictly decreasing subarrays. The problem can be solved using two pointers technique, start and end to mark the starting and ending of the subarray respectively.
We know that if an array of length L is strictly increasing, then all the subarrays inside this array will also be increasing. So, there will be a total of (L * (L + 1)) / 2 strictly increasing subarrays. So using two pointers, we keep on incrementing end to find the strictly increasing subarray and as soon as the subarray starts to decrease, we add count of all subarrays between start and end.
Similarly, if a array of length L is strictly is strictly decreasing, then all the subarrays inside this array will also be decreasing. So, there will be a total of (L * (L + 1)) / 2 strictly decreasing subarrays. So using two pointers, we keep on incrementing end to find the strictly decreasing subarray and as soon as the subarray starts to increase, we add count of all subarrays between start and end.
Below is the implementation of the above approach:
C++
// C++ Program to find the number of strictly increasing and
// decreasing subarrays
#include <bits/stdc++.h>
using namespace std;
// function to find the count of increasing subarrays
int countIncreasing(int arr[], int n)
{
// Initialize result
int cnt = 0;
// Initialize start and end pointers
int start = 0, end = 1;
// Traverse through the array
while (end < n) {
if (arr[end] <= arr[end - 1]) {
int len = end - start;
cnt += (len * (len + 1)) / 2;
start = end;
}
end++;
}
// Count the last remaining subarrays
int len = end - start;
cnt += ((len * (len + 1)) / 2);
return cnt;
}
// function to find the count of decreasing subarrays
int countDecreasing(int arr[], int n)
{
int cnt = 0; // Initialize result
// Initialize start and end pointers
int start = 0, end = 1;
// Traverse through the array
while (end < n) {
if (arr[end] >= arr[end - 1]) {
int len = end - start;
cnt += (len * (len + 1)) / 2;
start = end;
}
end++;
}
// Count the last remaining subarrays
int len = end - start;
cnt += ((len * (len + 1)) / 2);
return cnt;
}
// Driver program
int main()
{
int arr[] = { 80, 50, 60, 70, 40, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Count of strictly increasing subarrays is "
<< countIncreasing(arr, n) << endl;
cout << "Count of strictly decreasing subarrays is "
<< countDecreasing(arr, n) << endl;
return 0;
}
Java
// Java Program to find the number of strictly increasing
// and decreasing subarrays
public class GFG {
// Function to find the count of strictly increasing
// subarrays
public static int countIncreasing(int[] arr)
{
// Initialize result
int cnt = 0;
// Initialize start and end pointers
int start = 0, end = 1;
// Traverse through the array
while (end < arr.length) {
if (arr[end] <= arr[end - 1]) {
// Calculate the length of the increasing
// subarray
int len = end - start;
// Add the number of increasing subarrays
cnt += (len * (len + 1)) / 2;
// Update the start pointer
start = end;
}
end++;
}
// Count the last remaining subarrays
int len = end - start;
cnt += ((len * (len + 1)) / 2);
return cnt;
}
// Function to find the count of strictly decreasing
// subarrays
public static int countDecreasing(int[] arr)
{
int cnt = 0; // Initialize result
// Initialize start and end pointers
int start = 0, end = 1;
// Traverse through the array
while (end < arr.length) {
if (arr[end] >= arr[end - 1]) {
// Calculate the length of the decreasing
// subarray
int len = end - start;
// Add the number of decreasing subarrays
cnt += (len * (len + 1)) / 2;
// Update the start pointer
start = end;
}
end++;
}
// Count the last remaining subarrays
int len = end - start;
cnt += ((len * (len + 1)) / 2);
return cnt;
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 80, 50, 60, 70, 40, 40 };
System.out.println(
"Count of strictly increasing subarrays is "
+ countIncreasing(arr));
System.out.println(
"Count of strictly decreasing subarrays is "
+ countDecreasing(arr));
}
}
Python
# Python Program to find the number of strictly increasing
# and decreasing subarrays
# Function to find the count of strictly increasing subarrays
def count_increasing(arr):
# Initialize result
cnt = 0
# Initialize start and end pointers
start = 0
end = 1
# Traverse through the array
while end < len(arr):
if arr[end] <= arr[end - 1]:
# Calculate the length of the increasing subarray
length = end - start
# Add the number of increasing subarrays
cnt += (length * (length + 1)) // 2
# Update the start pointer
start = end
end += 1
# Count the last remaining subarrays
length = end - start
cnt += ((length * (length + 1)) // 2)
return cnt
# Function to find the count of strictly decreasing subarrays
def count_decreasing(arr):
# Initialize result
cnt = 0
# Initialize start and end pointers
start = 0
end = 1
# Traverse through the array
while end < len(arr):
if arr[end] >= arr[end - 1]:
# Calculate the length of the decreasing subarray
length = end - start
# Add the number of decreasing subarrays
cnt += (length * (length + 1)) // 2
# Update the start pointer
start = end
end += 1
# Count the last remaining subarrays
length = end - start
cnt += ((length * (length + 1)) // 2)
return cnt
# Driver code
arr = [80, 50, 60, 70, 40, 40]
print("Count of strictly increasing subarrays is", count_increasing(arr))
print("Count of strictly decreasing subarrays is", count_decreasing(arr))
C#
using System;
class GFG {
// Function to find the count of strictly increasing
// subarrays
static int CountIncreasing(int[] arr)
{
// Initialize result
int cnt = 0;
// Initialize start and end pointers
int start = 0;
int end = 1;
// Traverse through the array
while (end < arr.Length) {
if (arr[end] <= arr[end - 1]) {
// Calculate the length of the increasing
// subarray
int len = end - start;
// Add the number of increasing subarrays of
// the current length
cnt += (len * (len + 1)) / 2;
// Update the start pointer for the next
// increasing subarray
start = end;
}
end++;
}
// Count the last remaining subarrays
int remainingLen = end - start;
cnt += (remainingLen * (remainingLen + 1)) / 2;
return cnt;
}
// Function to find the count of strictly decreasing
// subarrays
static int CountDecreasing(int[] arr)
{
// Initialize result
int cnt = 0;
// Initialize start and end pointers
int start = 0;
int end = 1;
// Traverse through the array
while (end < arr.Length) {
if (arr[end] >= arr[end - 1]) {
// Calculate the length of the decreasing
// subarray
int len = end - start;
// Add the number of decreasing subarrays of
// the current length
cnt += (len * (len + 1)) / 2;
// Update the start pointer for the next
// decreasing subarray
start = end;
}
end++;
}
// Count the last remaining subarrays
int remainingLen = end - start;
cnt += (remainingLen * (remainingLen + 1)) / 2;
return cnt;
}
// Main method to drive the program
static void Main()
{
int[] arr = { 80, 50, 60, 70, 40, 40 };
// Function call to count strictly increasing
// subarrays
int increasingCount = CountIncreasing(arr);
Console.WriteLine(
"Count of strictly increasing subarrays is "
+ increasingCount);
// Function call to count strictly decreasing
// subarrays
int decreasingCount = CountDecreasing(arr);
Console.WriteLine(
"Count of strictly decreasing subarrays is "
+ decreasingCount);
}
}
JavaScript
// Function to find the count of strictly increasing subarrays
function countIncreasing(arr) {
let cnt = 0; // Initialize result
let start = 0;
let end = 1;
// Traverse through the array
while (end < arr.length) {
if (arr[end] <= arr[end - 1]) {
// Calculate the length of the increasing subarray
let len = end - start;
// Add the number of increasing subarrays of the current length
cnt += (len * (len + 1)) / 2;
// Update the start pointer for the next increasing subarray
start = end;
}
end++;
}
// Count the last remaining subarrays
let len = end - start;
cnt += (len * (len + 1)) / 2;
return cnt;
}
// Function to find the count of strictly decreasing subarrays
function countDecreasing(arr) {
let cnt = 0; // Initialize result
let start = 0;
let end = 1;
// Traverse through the array
while (end < arr.length) {
if (arr[end] >= arr[end - 1]) {
// Calculate the length of the decreasing subarray
let len = end - start;
// Add the number of decreasing subarrays of the current length
cnt += (len * (len + 1)) / 2;
// Update the start pointer for the next decreasing subarray
start = end;
}
end++;
}
// Count the last remaining subarrays
let len = end - start;
cnt += (len * (len + 1)) / 2;
return cnt;
}
// Driver function
function main() {
const arr = [80, 50, 60, 70, 40, 40];
const increasingCount = countIncreasing(arr);
const decreasingCount = countDecreasing(arr);
console.log("Count of strictly increasing subarrays is " + increasingCount);
console.log("Count of strictly decreasing subarrays is " + decreasingCount);
}
// Call the main function to execute the program
main();
OutputCount of strictly increasing subarrays is 9
Count of strictly decreasing subarrays is 8
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read