Monotonic Array - Problem

Imagine you're analyzing data trends - monotonic arrays are sequences that consistently move in one direction, never changing course!

An array is monotonic if it follows one of these patterns:

  • Monotone Increasing: Each element is greater than or equal to the previous one (nums[i] ≤ nums[j] for all i ≤ j)
  • Monotone Decreasing: Each element is less than or equal to the previous one (nums[i] ≥ nums[j] for all i ≤ j)

Given an integer array nums, determine if it maintains a monotonic pattern.

Examples:

  • [1, 2, 2, 3]true (increasing)
  • [6, 5, 4, 4]true (decreasing)
  • [1, 3, 2]false (changes direction)

Input & Output

example_1.py — Python
$ Input: [1,2,2,3]
Output: true
💡 Note: The array is monotone increasing (non-decreasing). Each element is greater than or equal to the previous one.
example_2.py — Python
$ Input: [6,5,4,4]
Output: true
💡 Note: The array is monotone decreasing (non-increasing). Each element is less than or equal to the previous one.
example_3.py — Python
$ Input: [1,3,2]
Output: false
💡 Note: The array changes direction: increases from 1 to 3, then decreases from 3 to 2. It's neither monotone increasing nor decreasing.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • Edge cases: Single element or empty arrays are considered monotonic

Visualization

Tap to expand
📈 Stock Trend Analysis AnalogyMonotonic Array = Consistent Stock TrendDay 1Day 2Day 3Day 4$1Start$3+$2 📈$2-$1 📉$4+$2 📈🚨 Mixed Trends Detected!✓ Increasing trend seen: Day 1 → Day 2 ($1 → $3)✓ Decreasing trend seen: Day 2 → Day 3 ($3 → $2)Result: NOT MONOTONIC (Volatile stock! 📊)✅ Monotonic Examples:Bull Market: [100, 105, 105, 110] 📈Only increases or stays sameBear Market: [100, 95, 90, 90] 📉Only decreases or stays same💡 Algorithm Insight:Like a smart trader, we track trends as we go. The moment we see bothrising AND falling patterns, we know the stock is volatile (not monotonic)!
Understanding the Visualization
1
Trend Detection
As we scan through daily prices, we note any increases or decreases
2
Pattern Recognition
If we see both upward AND downward movements, the stock is volatile (not monotonic)
3
Early Warning
The moment we detect mixed trends, we know it's not a consistent pattern
Key Takeaway
🎯 Key Insight: We only need to track if we've seen BOTH increasing and decreasing trends. If we see both, it's not monotonic - just like a volatile stock that goes both up and down!
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
96.2K Views
Medium Frequency
~15 min Avg. Time
2.8K 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