Problem
An array is monotonic if it is either monotone increasing or monotone decreasing.
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]
.
Given an integer array nums
, return true
if the given array is monotonic, orfalse
otherwise.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
-10^5 <= nums[i] <= 10^5
Solution
Method 1 - One Pass Check
Intuition
Check if the array is monotone increasing or monotone decreasing in a single pass.
Approach
Iterate through the array, track if it is increasing or decreasing. If both are false at any point, return false.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— One pass through the array. - 🧺 Space complexity:
O(1)
— Only a few variables used.