Magicsheet logo

Longest Strictly Increasing or Strictly Decreasing Subarray

Easy
100%
Updated 6/1/2025

Longest Strictly Increasing or Strictly Decreasing Subarray

What is this problem about?

This problem gives you an array of integers and asks you to find the length of the longest contiguous subarray that is either strictly increasing or strictly decreasing. For example, in [1, 4, 3, 2, 5], [1, 4] is strictly increasing (length 2), and [4, 3, 2] is strictly decreasing (length 3). The answer would be 3.

Why is this asked in interviews?

This is a classic introductory array traversal problem. Interviewers use it as a warm-up or screening question because it tests fundamental loop constructs and variable management. It evaluates whether a candidate can track multiple running states (increasing vs. decreasing) simultaneously in a single pass without getting their logic tangled.

Algorithmic pattern used

The best approach uses a Single Pass / Sliding Window pattern. You iterate through the array once, maintaining two counters: one for the current strictly increasing sequence and one for the current strictly decreasing sequence. If the next number is greater, you increment the increasing counter and reset the decreasing counter to 1. If it's smaller, you increment the decreasing counter and reset the increasing counter. If they are equal, you reset both.

Example explanation

Array: [5, 4, 4, 7, 8] Initialize: inc = 1, dec = 1, max_len = 1.

  • Compare 5 and 4: 4 is smaller. dec becomes 2. inc resets to 1. max_len = 2.
  • Compare 4 and 4: Equal! Both inc and dec reset to 1.
  • Compare 4 and 7: 7 is greater. inc becomes 2. dec resets to 1. max_len = 2.
  • Compare 7 and 8: 8 is greater. inc becomes 3. dec resets to 1. max_len = 3. The maximum length across the entire array is 3 (from [4, 7, 8]).

Common mistakes candidates make

Candidates sometimes forget to handle adjacent duplicate numbers properly. If two numbers are identical (e.g., [2, 2]), the sequence is neither strictly increasing nor strictly decreasing. Failing to reset the counters to 1 upon finding duplicates will result in an artificially inflated length. Another common error is forgetting to initialize the max_len to 1 for non-empty arrays.

Interview preparation tip

For this interview pattern, prioritize clean, readable code. You can easily solve this in one loop with a few simple if-else if-else statements. Avoid writing two completely separate loops (one for increasing, one for decreasing), as doing it in one pass demonstrates better engineering maturity and code conciseness.

Similar Questions