↓Skip to main content
  1. LeetCode/

LeetCode 896: Monotonic Array

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-09-24

  • Submissions: Wrong Answer ×3 → Accepted ×3

Approach
#

Monotonic has two directions and is non-strict (equal neighbors are fine). In one pass record whether any rise and any fall occur; they cannot both happen (Array Template 1).

My Attempts
#

The first two checked only one direction: allowing only non-increasing made [0, 3] return False, and only non-decreasing made [1, 0] return False. Attempt 3 checked both but with strict < and >: [0, 0] returned False. Switching to <= and >= passed.

Solution
#

class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        up = down = False
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                up = True
            elif nums[i] < nums[i - 1]:
                down = True
        return not (up and down)

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Consider both directions.
  • Use <= and >=; equal neighbors keep it monotonic.

Interview Explanation
#

In one pass I record whether a rise and a fall occur; the array is monotonic unless both do, and equal neighbors do not matter. Time O(n), space O(1).

Related

LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 860: Lemonade Change
·2 mins
LeetCode Easy Array Greedy
LeetCode 860 note: track only the counts of $5 and $10 bills; for $15 change prefer 10 + 5, since $5 bills are more versatile
LeetCode 867: Transpose Matrix
·1 min
LeetCode Easy Array Matrix Simulation
LeetCode 867 note: the transpose is n × m with res[j][i] = matrix[i][j]; in Python, zip(*matrix)
LeetCode 821: Shortest Distance to a Character
·2 mins
LeetCode Easy Array Two-Pointers String
LeetCode 821 note: one left-to-right pass for the distance to the nearest c on the left, then a right-to-left pass taking the minimum