Count of indices in Array having all prefix elements less than all in suffix
Last Updated :
23 Jul, 2025
Given an array arr[], the task is to calculate the total number of indices where all elements in the left part is less than all elements in the right part of the array.
Examples:
Input: arr[] = {1, 5, 4, 2, 3, 8, 7, 9}
Output: 3
Explanation:
- Lets consider left part = [1], right part = [5, 4, 2, 3, 8, 7, 9]
Here, leftMax (1) < rightMin (2). So, it can be considered as sorted point. - Again, If we consider left part = [1, 5, 4, 2, 3], right part = [8, 7, 9]
Here also, leftMax < rightMin, So, it can also be considered as sorted point. - Similarly, If we consider left part = [1, 5, 4, 2, 3, 8, 7], right part = [9]
Here, leftMax < rightMin, So, it can also be considered as sorted point.
Hence, total 3 sorted points are found.
Input: arr[] = {5, 2, 3, 4, 1}
Output: 0
Naive Approach:
The naive approach is that we traverse each element of the array and for each element find maximum element say max in the left side which is including itself also and find minimum element say min in the right side which is after ith element. Finding maximum and minimum will be requiring another loop traversal. Now, check if max is less than min or not. If lesser then increase the count of elements, else continue.
Algorithm:
- Define function countIndices(arr, n) that takes an integer array 'arr' and its size 'n' as input.
- Initialize a variable 'count' to 0
- Traverse the array 'arr' from index 0 to n-1:
- Initialize a variable 'max_left' to INT_MIN
- Traverse the left side of 'arr' including the current element and find the maximum element among them, store it in 'max_left'
- Initialize a variable 'min_right' to INT_MAX
- Traverse the right side of 'arr' after the current element and find the minimum element among them, store it in 'min_right'
- If the value of 'min_right' is not INT_MAX and 'max_left' is less than 'min_right', then increment the value of 'count'.
- Return the value of 'count'.
- Define the main function
- Initialize an integer array 'arr' with given elements and its size 'n' to the size of the array
- Call the function 'countIndices' with 'arr' and 'n' as input
- Print the returned value from the function
Below is the implementation of the approach:
C++
// C++ code for the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return total count
// of sorted points in the array
int countIndices(int arr[], int n) {
int count = 0;
// Traverse through each element of the array
for (int i = 0; i < n; i++) {
int max_left = INT_MIN;
int j;
// Find maximum element in left side
for (j = 0; j <= i; j++) {
max_left = max(max_left, arr[j]);
}
int min_right = INT_MAX;
// Find minimum element in right side
for (int k = i + 1; k < n; k++) {
min_right = min(min_right, arr[k]);
}
// Check if max is less than min or not
if (min_right != INT_MAX && max_left < min_right) {
count++;
}
}
return count;
}
// Driver Code
int main() {
// Input array
int arr[] = { 1, 5, 4, 2, 3, 8, 7, 9 };
int n = sizeof(arr) / sizeof(int);
// Function Call
int result = countIndices(arr, n);
cout << result << endl;
return 0;
}
Java
// Java code for the approach
import java.io.*;
import java.util.*;
public class GFG {
// Function to return total count
// of sorted points in the array
static int countIndices(int arr[], int n) {
int count = 0;
// Traverse through each element of the array
for (int i = 0; i < n; i++) {
int max_left = Integer.MIN_VALUE;
int j;
// Find maximum element in left side
for (j = 0; j <= i; j++) {
max_left = Math.max(max_left, arr[j]);
}
int min_right = Integer.MAX_VALUE;
// Find minimum element in right side
for (int k = i + 1; k < n; k++) {
min_right = Math.min(min_right, arr[k]);
}
// Check if max is less than min or not
if (min_right != Integer.MAX_VALUE && max_left < min_right) {
count++;
}
}
return count;
}
// Driver Code
public static void main(String[] args) {
// Input array
int arr[] = { 1, 5, 4, 2, 3, 8, 7, 9 };
int n = arr.length;
// Function Call
int result = countIndices(arr, n);
System.out.println(result);
}
}
// This code has been contributed by Pushpesh Raj
Python3
# Function to return the total count of sorted points in the array
def countIndices(arr, n):
count = 0
# Traverse through each element of the array
for i in range(n):
max_left = float("-inf")
# Find the maximum element on the left side
for j in range(i + 1):
max_left = max(max_left, arr[j])
min_right = float("inf")
# Find the minimum element on the right side
for k in range(i + 1, n):
min_right = min(min_right, arr[k])
# Check if the maximum on the left is less than the minimum on the right
if min_right != float("inf") and max_left < min_right:
count += 1
return count
# Driver Code
if __name__ == "__main__":
# Input array
arr = [1, 5, 4, 2, 3, 8, 7, 9]
n = len(arr)
# Function Call
result = countIndices(arr, n)
print(result)
C#
using System;
class GFG
{
// Function to return total count
// of sorted points in the array
static int CountIndices(int[] arr)
{
int count = 0;
int n = arr.Length;
// Traverse through each element of the array
for (int i = 0; i < n; i++)
{
int maxLeft = int.MinValue;
int j;
// Find maximum element in left side
for (j = 0; j <= i; j++)
{
maxLeft = Math.Max(maxLeft, arr[j]);
}
int minRight = int.MaxValue;
// Find minimum element in right side
for (int k = i + 1; k < n; k++)
{
minRight = Math.Min(minRight, arr[k]);
}
// Check if max is less than min or not
if (minRight != int.MaxValue && maxLeft < minRight)
{
count++;
}
}
return count;
}
// Driver Code
static void Main()
{
// Input array
int[] arr = { 1, 5, 4, 2, 3, 8, 7, 9 };
// Function Call
int result = CountIndices(arr);
Console.WriteLine(result);
}
}
JavaScript
function GFG(arr) {
let count = 0;
// Traverse through each element of
// the array
for (let i = 0; i < arr.length; i++) {
let max_left = -Infinity;
for (let j = 0; j <= i; j++) {
max_left = Math.max(max_left, arr[j]);
}
let min_right = Infinity;
// Find minimum element in the
// right side
for (let k = i + 1; k < arr.length; k++) {
min_right = Math.min(min_right, arr[k]);
}
// Check if max is less than min or not
if (min_right !== Infinity && max_left < min_right) {
count++;
}
}
return count;
}
// Driver Code
const arr = [1, 5, 4, 2, 3, 8, 7, 9];
// Function Call
const result = GFG(arr);
console.log(result);
Time Complexity: O(n*n) where n is size of input array. This is because two nested for loops are being executed in function countIndices.
Auxiliary Space: O(1) as no extra space has been used.
Approach: The approach is based on the following idea:
The idea to solve the problem is by traversing the array and initialize two arrays to store the left part of the array and the right part of the array.
Then check if the maximum element of the left part of the array is less than the minimum element of the right part of the array.
If this condition is satisfied it is the sorted point and hence, increment the count by one and so on.
Follow the steps below to solve the given problem:
- Initialize Max = INT_MIN, Min = INT_MAX and Count = 0
- Now, create two arrays left and right of size N.
- Run one loop from start to end.
- In each iteration update Max as Max = max(Max, arr[i]) and also assign left[i] = Max
- Run another loop from end to start.
- In each iteration update Min as Min = min(Min, arr[i]) and also assign right[i] = Min
- Traverse the array from start to end.
- If, left[i] <= right[i+1], then a sorted point is achieved,
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to return total count
// of sorted points in the array
int countSortedPoints(int* arr, int N)
{
int left[N];
int right[N];
// Initialize the variables
int Min = INT_MAX;
int Max = INT_MIN;
int Count = 0;
// Make Maximum array
for (int i = 0; i < N; i++) {
Max = max(arr[i], Max);
left[i] = Max;
}
// Make Minimum array
for (int i = N - 1; i >= 0; i--) {
Min = min(arr[i], Min);
right[i] = Min;
}
// Count of sorted points
for (int i = 0; i < N - 1; i++) {
if (left[i] <= right[i + 1])
Count++;
}
// Return count of sorted points
return Count;
}
// Driver Code
int main()
{
int arr[] = { 1, 5, 4, 2, 3, 8, 7, 9 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countSortedPoints(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
class GFG {
// Function to return total count
// of sorted points in the array
static int countSortedPoints(int []arr, int N)
{
int []left = new int[N];
int []right = new int[N];
// Initialize the variables
int Min = Integer.MAX_VALUE;
int Max = Integer.MIN_VALUE;
int Count = 0;
// Make Maximum array
for (int i = 0; i < N; i++) {
Max = Math.max(arr[i], Max);
left[i] = Max;
}
// Make Minimum array
for (int i = N - 1; i >= 0; i--) {
Min = Math.min(arr[i], Min);
right[i] = Min;
}
// Count of sorted points
for (int i = 0; i < N - 1; i++) {
if (left[i] <= right[i + 1])
Count++;
}
// Return count of sorted points
return Count;
}
// Driver Code
public static void main (String[] args) {
int arr[] = { 1, 5, 4, 2, 3, 8, 7, 9 };
int N = arr.length;
// Function call
System.out.print(countSortedPoints(arr, N));
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python3 implementation of the approach
INT_MIN = -2147483648
INT_MAX = 2147483647
# Function to return total count
# of sorted points in the array
def countSortedPoints(arr, N):
left = [0 for i in range(N)]
right = [0 for i in range(N)]
# Initialize the variables
Min = INT_MAX
Max = INT_MIN
Count = 0
# Make Maximum array
for i in range(N):
Max = max(arr[i], Max)
left[i] = Max
# Make Minimum array
for i in range(N - 1, -1, -1):
Min = min(arr[i], Min)
right[i] = Min
# Count of sorted points
for i in range(0, N - 1):
if (left[i] <= right[i + 1]):
Count += 1
# Return count of sorted points
return Count
# Driver Code
arr = [1, 5, 4, 2, 3, 8, 7, 9]
N = len(arr)
# Function call
print(countSortedPoints(arr, N))
# This code is contributed by shinjanpatra
C#
// C# program for the above approach
using System;
class GFG
{
// Function to return total count
// of sorted points in the array
static int countSortedPoints(int []arr, int N)
{
int []left = new int[N];
int []right = new int[N];
// Initialize the variables
int Min = Int32.MaxValue;
int Max = Int32.MinValue;
int Count = 0;
// Make Maximum array
for (int i = 0; i < N; i++) {
Max = Math.Max(arr[i], Max);
left[i] = Max;
}
// Make Minimum array
for (int i = N - 1; i >= 0; i--) {
Min = Math.Min(arr[i], Min);
right[i] = Min;
}
// Count of sorted points
for (int i = 0; i < N - 1; i++) {
if (left[i] <= right[i + 1])
Count++;
}
// Return count of sorted points
return Count;
}
// Driver Code
public static void Main()
{
int []arr = { 1, 5, 4, 2, 3, 8, 7, 9 };
int N = arr.Length;
// Function call
Console.Write(countSortedPoints(arr, N));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript program for the above approach
const INT_MIN = -2147483647 - 1;
const INT_MAX = 2147483647;
// Function to return total count
// of sorted points in the array
const countSortedPoints = (arr, N) => {
let left = new Array(N).fill(0);
let right = new Array(N).fill(0);
// Initialize the variables
let Min = INT_MAX;
let Max = INT_MIN;
let Count = 0;
// Make Maximum array
for (let i = 0; i < N; i++) {
Max = Math.max(arr[i], Max);
left[i] = Max;
}
// Make Minimum array
for (let i = N - 1; i >= 0; i--) {
Min = Math.min(arr[i], Min);
right[i] = Min;
}
// Count of sorted points
for (let i = 0; i < N - 1; i++) {
if (left[i] <= right[i + 1])
Count++;
}
// Return count of sorted points
return Count;
}
// Driver Code
let arr = [1, 5, 4, 2, 3, 8, 7, 9];
let N = arr.length;
// Function call
document.write(countSortedPoints(arr, N));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem