Check whether an integer array is monotonic (entirely non-decreasing or non-increasing)
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Other
Overview: Decide whether an integer array is monotonic, meaning entirely non-decreasing or entirely non-increasing, with equal neighbors allowed. It tests a single linear pass over adjacent pairs, the reasoning for why neighbor checks are enough, and handling of repeated values.
Constraints
- 1 <= len(nums) <= 10^5
- -10^5 <= nums[i] <= 10^5
- No value can exceed 2^31-1, so every value fits in a signed 32-bit integer.
Examples
Input: ([1, 2, 2, 3],)
Expected Output: True
Explanation: Source example 1: every step rises or stays equal, and the repeated 2 is allowed.
Input: ([6, 5, 4, 4],)
Expected Output: True
Explanation: Source example 2: every step drops or stays equal, ending on a repeated 4.
Hints
- The definition compares every pair with i <= j. Ask whether looking at fewer pairs can decide the same question.
- Equal neighbors fit both directions, so until a strict rise or drop appears, the array could still be either kind.
- Try your idea on an array that starts with repeated values, and on one that changes direction only at its last step.