Knowledge Guide
HomeDSACompany Practice

easy Monotonic Array

Problem Statement

Given an array nums containing integers, return true if the given array is monotonic. Otherwise, return false.

An array is monotonic if it follows below conditions.

Examples

Try it yourself

Try solving this question here:

✅ Solution Monotonic Array

Problem Statement

Given an array nums containing integers, return true if the given array is monotonic. Otherwise, return false.

An array is monotonic if it follows below conditions.

  • An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
  • An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].

Examples

  • Example 1:

    • Input: nums = [1, 5, 10, 10, 15, 16, 90]
    • Expected Output: true
    • Justification: The array consistently ascends or remains equal, thus it is monotone increasing.
  • Example 2:

    • Input: nums = [9, 4, 2, 2, 0]
    • Expected Output: true
    • Justification: The array values either decrease or stay the same throughout, making it monotone decreasing.
  • Example 3:

    • Input: nums = [7, 8, 7, 7]
    • Expected Output: false
    • Justification: Array is not monotonic as 8 is in between two 7.

Solution

To solve this problem, we start by recognizing that a monotonic array has one of two characteristics: it's either entirely non-decreasing or entirely non-increasing. This observation is crucial because it allows us to simplify our checks to just two conditions across the array's entirety. We believe this approach is effective because it directly leverages the definition of monotonic arrays, enabling us to verify the condition with a single pass through the array. By evaluating adjacent elements from start to finish, we can determine if the array deviates from either monotonic condition. This method is efficient and straightforward, making it an ideal solution.

In the first step, we'll assess if the array is non-decreasing by comparing each element to its successor. Similarly, we'll check if it's non-increasing. If either condition holds for the entire array, our function will return true; otherwise, false. This dual-path check ensures we correctly handle arrays that are constant or have equal elements throughout, aligning with our monotonic criteria.

Step-by-Step Algorithm

  1. Initialize Two Flags: Start by declaring two boolean variables, isNonDecreasing and isNonIncreasing, and set them both to true. These flags will help us track whether the array is non-decreasing or non-increasing, respectively.

  2. Iterate Through the Array: Loop through the array from the first element to the second-last element. We compare each element with its next element to determine the array's trend. This is because we need at least two elements to compare and determine a trend.

  3. Check Non-Decreasing Trend: During each iteration, compare the current element with the next element. If the current element is greater than the next element, set isNonDecreasing to false. This indicates that the array cannot be non-decreasing because we found at least one instance where a later element is smaller than its predecessor.

  4. Check Non-Increasing Trend: Similarly, if the current element is less than the next element, set isNonIncreasing to false. This step checks for a non-increasing trend. Finding a later element larger than its predecessor means the array cannot be non-increasing.

  5. Determine Monotonicity: After completing the loop, check the flags. If either isNonDecreasing or isNonIncreasing is still true, the array is monotonic. Return true in this case. If both flags are false, the array is not monotonic, so return false.

Algorithm Walkthrough

Let's consider the input: nums = [1, 5, 10, 10, 15, 16, 90]

  1. Initialize Flags:

    • isNonDecreasing = true
    • isNonIncreasing = true
  2. First Iteration (1 -> 5):

    • Compare 1 and 5: Since 1 < 5, the array might be non-decreasing. Change isNonIncreasing to false.
  3. Second Iteration (5 -> 10):

    • Compare 5 and 10: Since 5 < 10, still possibly non-decreasing. No change to flags.
  4. Third Iteration (10 -> 10):

    • Compare 10 and 10: Equal elements do not affect monotonicity. No change to flags.
  5. Fourth Iteration (10 -> 15):

    • Compare 10 and 15: Since 10 < 15, the array continues to potentially be non-decreasing. No change to flags.
  6. Fifth Iteration (15 -> 16):

    • Compare 15 and 16: 15 < 16 supports non-decreasing trend. No change to flags.
  7. Sixth Iteration (16 -> 90):

    • Compare 16 and 90: 16 < 90 continues to support a non-decreasing trend. No change to flags.
  8. Determine Monotonicity:

    • After the final iteration, isNonDecreasing is false, and isNonIncreasing remains true.
    • Since isNonIncreasing is true, the array [1, 5, 10, 10, 15, 16, 90] is determined to be monotonic.

Code

java
public class Solution {

  // Method to check if the array is monotonic
  public boolean isMonotonic(int[] nums) {
    boolean isNonDecreasing = true;
    boolean isNonIncreasing = true;

    // Iterate through array to check for non-decreasing or non-increasing pattern
    for (int i = 0; i < nums.length - 1; i++) {
      if (nums[i] > nums[i + 1]) isNonDecreasing = false;
      if (nums[i] < nums[i + 1]) isNonIncreasing = false;
    }

    // Return true if either condition is met
    return isNonDecreasing || isNonIncreasing;
  }

  public static void main(String[] args) {
    Solution solution = new Solution();
    // Test with the provided examples
    System.out.println(
      solution.isMonotonic(new int[] { 1, 5, 10, 10, 15, 16, 90 })
    ); // Example 1
    System.out.println(solution.isMonotonic(new int[] { 9, 4, 2, 2, 0 })); // Example 2
    System.out.println(solution.isMonotonic(new int[] { 7, 8, 7, 7 })); // Example 3
  }
}

Complexity Analysis

Time Complexity

The time complexity of the algorithm is , where n is the length of the input array. This is because the algorithm iterates through the array exactly once to check if it is either non-decreasing or non-increasing.

Space Complexity

The space complexity complexity of the algorithm is . The algorithm uses a fixed amount of space (a couple of boolean variables) regardless of the input array size, indicating constant space complexity.

🤖 Don't fully get this? Learn it with Claude

Stuck on Monotonic Array? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Monotonic Array** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Monotonic Array** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Monotonic Array**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Monotonic Array**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes