Advertisement
Home Data Structure Arrays Find Longest Decreasing Subarray

Find Longest Decreasing Subarray

1
Advertisement

Title: Find Longest Decreasing Subarray

In this guide, you’ll learn how to find the length of the longest contiguous subarray in which the elements keep strictly decreasing. This is a classic array scanning problem that interviewers use to test whether you can track a running state across a single pass instead of reaching for nested loops or extra data structures.

Understanding the Problem

Given an integer array nums, you need to find the length of the longest subarray where each element is strictly smaller than the one before it. A subarray must use consecutive elements, so you cannot skip indices or reorder values. For example, in [9, 7, 5, 8, 6, 4, 2, 10], the run 8, 6, 4, 2 is the longest strictly decreasing stretch, giving an answer of 4.

This differs from the longest increasing subsequence problem in two important ways. First, the elements must be contiguous rather than scattered anywhere in the array. Second, you only need the length of the run, not the elements that make it up. That contiguity is what lets you solve the whole problem in a single linear pass with constant extra memory.

Approach

  1. Handle the trivial case first: if nums is null or empty, throw an exception since there is no valid subarray to measure.
  2. Initialize currentLength and maxLength to 1, since any single element is a decreasing subarray of length 1 by itself.
  3. Walk the array from index 1 to the end, comparing each element nums[i] with the previous element nums[i - 1].
  4. If nums[i] is strictly less than nums[i - 1], the decreasing run continues, so increment currentLength.
  5. Otherwise the run is broken, so reset currentLength back to 1 because the current element starts a fresh potential run.
  6. After each comparison, update maxLength to the larger of its current value and currentLength.
  7. Return maxLength once the loop finishes scanning the entire array.

Java Program

Java
public class LongestDecreasingSubarray {

    public static int longestDecreasingSubarray(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new IllegalArgumentException("Input array must not be empty");
        }

        int maxLength = 1;
        int currentLength = 1;

        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < nums[i - 1]) {
                currentLength++;
            } else {
                currentLength = 1;
            }
            maxLength = Math.max(maxLength, currentLength);
        }

        return maxLength;
    }

    public static void main(String[] args) {
        int[] nums = {9, 7, 5, 8, 6, 4, 2, 10};
        int result = longestDecreasingSubarray(nums);
        System.out.println("Length of longest decreasing subarray: " + result);
    }
}

Explanation of the Program

The method longestDecreasingSubarray keeps two counters as it scans the array once. currentLength tracks how long the decreasing run ending at the current index is, while maxLength remembers the best run seen anywhere so far.

  • The if (nums == null || nums.length == 0) check guards against an invalid input before any indexing happens.
  • The loop starts at i = 1 because the first element has no predecessor to compare against; it already counts toward a run of length 1.
  • The comparison nums[i] < nums[i - 1] is strict, which matches the problem’s definition of decreasing and excludes runs of equal values.
  • Math.max(maxLength, currentLength) is called on every iteration, not just when a run breaks, so the answer is correct even if the longest run extends all the way to the last element.

Step-by-Step Trace

Trace the algorithm on [12, 9, 15, 11, 7, 3, 20]. The longest strictly decreasing run is 15, 11, 7, 3, so the expected output is 4.

Iteration (i)nums[i]nums[i] < nums[i-1]?currentLength (before)currentLength (after)maxLength
19yes122
215no212
311yes122
47yes233
53yes344
620no414

At the end of each iteration, currentLength holds the length of the decreasing run that ends at index i, and maxLength holds the longest such run observed in nums[0..i].

Examples

Example 1: A Run in the Middle

The longest decreasing run sits in the middle of the array, surrounded by values that break it on both sides.

Java
int[] nums = {9, 7, 5, 8, 6, 4, 2, 10};
System.out.println(longestDecreasingSubarray(nums));
// Output: 4

Example 2: Strictly Increasing Array

When no two consecutive elements ever decrease, every run has length 1, so the answer is the minimum possible value.

Java
int[] nums = {1, 2, 3, 4};
System.out.println(longestDecreasingSubarray(nums));
// Output: 1

Example 3: Single-Element Array

A one-element array has no pair to compare, so it trivially forms a decreasing subarray of length 1.

Java
int[] nums = {5};
System.out.println(longestDecreasingSubarray(nums));
// Output: 1

Common Mistakes to Avoid

These are the mistakes that most often slip into a first attempt at this problem.

  • Initializing maxLength to 0 – this makes a single-element array incorrectly return 0 instead of 1, since the loop body never executes to raise it. Initialize both maxLength and currentLength to 1.
  • Using <= instead of strict < – this counts equal adjacent values like [5, 5, 5] as part of a decreasing run, inflating the answer. Use nums[i] < nums[i - 1] since the problem requires strictly decreasing values.
  • Resetting currentLength to 0 on a broken run – this undercounts the length because the current element itself always starts a valid run of at least 1. Reset currentLength to 1, not 0.
  • Comparing nums[i] to nums[0] instead of nums[i – 1] – this measures distance from the start of the array rather than the length of a contiguous decreasing run, producing wrong answers on arrays with more than one run. Always compare each element to its immediate predecessor.

Edge Cases to Test

Before considering this problem solved, walk through the inputs that most often break a careless implementation.

  • Empty array
  • Single-element array
  • All elements equal
  • Strictly increasing array
  • Entire array strictly decreasing
  • Negative numbers present
  • Integer.MIN_VALUE and Integer.MAX_VALUE present
  • Null array reference

Additional Considerations

The algorithm makes a single pass over the array, so its time complexity is O(n) where n is the length of nums. It only tracks three integer variables regardless of input size, giving O(1) extra space; no auxiliary array or recursion stack is needed.

Because the comparison only checks nums[i] < nums[i - 1] and never subtracts the two values, extreme inputs such as Integer.MIN_VALUE and Integer.MAX_VALUE cannot cause an overflow the way a difference-based comparison would.

Interview Follow-up Questions

Once you can solve the base problem, expect an interviewer to push further with questions like these.

  • What if the array is sorted in increasing order? – the loop body comparison never succeeds, so the answer collapses to 1 regardless of array length.
  • What if you need to return the actual subarray instead of just its length? – track the starting index of the current run alongside currentLength, and copy nums[start..i] whenever a new maximum is found.
  • What if decreasing should also allow equal adjacent values (non-increasing)? – broaden the loop comparison to also match equal neighbors; the rest of the algorithm is unchanged.
  • What if the array arrives as a stream too large to hold in memory? – keep only the previous element, currentLength, and maxLength in memory, and process each new value exactly once as it arrives; the algorithm is already a single forward pass, so it is naturally stream-friendly.

Conclusion

Finding the longest decreasing subarray is a great example of how a single well-chosen pair of counters can replace nested loops entirely. Once you’re comfortable tracking currentLength and maxLength together, the same pattern adapts easily to related problems like the longest increasing run or the longest subarray with equal adjacent elements. You can learn more about array-based interview problems in our Arrays category.