Monotonic Array — LeetCode 896 Python Solution

EasyArray
Problem
#896
Reading time
2 min

The 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].

Example

Input
nums = [1,2,2,3]
Output
true

Python solution

Python
class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        asc = all(a <= b for a, b in pairwise(nums))
        desc = all(a >= b for a, b in pairwise(nums))
        return asc or desc

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 896. Monotonic Array?
LeetCode 896. Monotonic Array is rated Easy on LeetCode.
What is the time complexity of LeetCode 896. Monotonic Array?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 896. Monotonic Array?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 896. Monotonic Array cover?
LeetCode 896. Monotonic Array is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview