VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-subarray-length/

⇱ Longest Subarray Length - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray Length

Last Updated : 15 Sep, 2025

Given an array of integers arr[]. Find the length of the longest subarray such that all the elements of the subarray are smaller than or equal to the length of the subarray.

Example:

Input: arr[] = [1, 2, 3]
Output: 3
Explanation: The longest subarray is the entire array itself [1, 2, 3], which has a length of 3. All elements in the subarray are less than or equal to 3.

Input: arr[] = [6, 4, 2, 5]
Output: 0
Explanation: There is no subarray where all elements are less than or equal to the length of the subarray. The longest subarray is empty, which has a length of 0.

[Naive Approach] By Checking All The Subarray - O(n2) Time and O(1) Space

The idea is to check every possible subarray, compute its maximum element, and verify if the subarray length is greater than or equal to this maximum. If valid, update the answer with the maximum length found.


Output
3

[Expected Approach] Using Stack - O(n) Time and O(n) Space

Intuition

If we are given an array, along with its size and maximum element, we can directly validate whether the array is valid or not (length of array >= maximum element).

What if we treat every element as the maximum element and then try to find the range where that element can actually remain the maximum? So the problem reduces to: For every element arr[i], find the largest window [L..R] where arr[i] is the maximum.

How to find that window?

To find out the window for which an element arr[i] is the maximum:

  • On the left side, keep moving until you find an element greater than arr[i]. The window cannot extend beyond this point, because then arr[i] would no longer be the maximum.
  • On the right side, do the same stop as soon as you encounter an element greater than arr[i].

So, the element arr[i] is the maximum in the subarray that starts just after the greater element on the left and ends just before the greater element on the right (windowLength = (NGE[i] - PGE[i] - 1)).

Check validity

If windowLength >= arr[i], then it forms a valid subarray and keep track of the maximum such length.


Output
3
Comment
Article Tags:
Article Tags: