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 - Single Pass Approach INPUT nums = [1, 2, 2, 3] 1 i=0 2 i=1 2 i=2 3 i=3 Comparing adjacent pairs: 1 <= 2 2 <= 2 2 <= 3 Initialize flags: increasing=true decreasing=true Track violations in a single pass ALGORITHM STEPS 1 Initialize Flags Set inc=true, dec=true 2 Loop Through Array Compare nums[i] vs nums[i+1] 3 Track Violations If a[i] > a[i+1]: inc=false If a[i] < a[i+1]: dec=false 4 Return Result Return inc OR dec Trace for [1,2,2,3]: i=0: 1<=2 inc=T dec=F i=1: 2<=2 inc=T dec=F i=2: 2<=3 inc=T dec=F Result: T OR F = TRUE FINAL RESULT Array is Monotonic! OK Output: true The array [1,2,2,3] is monotone increasing since each element is <= the next. Complexity Time: O(n) | Space: O(1) Key Insight: Instead of checking both directions separately, we track violations in a single pass. If we find any nums[i] > nums[i+1], the array can't be increasing. If nums[i] < nums[i+1], it can't be decreasing. The array is monotonic if at least one direction remains valid (no violations found for that direction). TutorialsPoint - Monotonic Array | Single Pass - Track Violations
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