#896

Monotonic Array

Easy
ArrayArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a single pass through the array to determine if it is monotonic. This is efficient and leverages the fact that we only need to check the relationship between adjacent elements.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two flags, isIncreasing and isDecreasing, to true.
  2. 2Step 2: Loop through the array from the first to the second last element.
  3. 3Step 3: Compare each element with the next one; if any element is greater than the next, set isIncreasing to false, and if any element is less than the next, set isDecreasing to false.
  4. 4Step 4: After the loop, return true if either isIncreasing or isDecreasing is true.
solution.py9 lines
1def isMonotonic(nums):
2    isIncreasing = True
3    isDecreasing = True
4    for i in range(len(nums) - 1):
5        if nums[i] > nums[i + 1]:
6            isIncreasing = False
7        if nums[i] < nums[i + 1]:
8            isDecreasing = False
9    return isIncreasing or isDecreasing

Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) as we are using a constant amount of space for the flags.

  • 1An array can be monotonic if it is either non-decreasing or non-increasing.
  • 2The optimal solution leverages the relationship between adjacent elements to minimize checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.