Monotonic Array - 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, or false otherwise.

Input & Output

Example 1 — Non-decreasing Array
$ Input: nums = [1,2,2,3]
Output: true
💡 Note: Array is non-decreasing: 1 ≤ 2 ≤ 2 ≤ 3. Since it satisfies the monotonic increasing property, return true.
Example 2 — Non-monotonic Array
$ Input: nums = [6,5,4,4]
Output: true
💡 Note: Array is non-increasing: 6 ≥ 5 ≥ 4 ≥ 4. Since it satisfies the monotonic decreasing property, return true.
Example 3 — Mixed Pattern
$ Input: nums = [1,3,2]
Output: false
💡 Note: Array has both increasing (1<3) and decreasing (3>2) transitions, so it's not monotonic.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Monotonic Array: Check for Consistent Pattern✓ Monotonic (Increasing)1223✗ Not Monotonic132Algorithm: Single Pass with Pattern Tracking1. Track increasing and decreasing flags2. Compare adjacent elements: nums[i] vs nums[i+1]3. Return false if both patterns detectedKey Insight: Monotonic means NEVER both ↗ and ↘Time: O(n) | Space: O(1)
Understanding the Visualization
1
Input Array
Given array with elements to check for monotonic property
2
Check Pattern
Verify if array is only increasing, only decreasing, or constant
3
Result
Return true if monotonic, false if mixed pattern
Key Takeaway
🎯 Key Insight: An array is monotonic if it never exhibits both increasing and decreasing patterns
Asked in
Facebook 28 Amazon 15 Google 12
180.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen