File: monotonic-array/solution.py

Date: 2026-06-06

Time: 18:06

monotonic-array/solution.py

Purpose

This file solves LeetCode 896 — Monotonic Array. It determines whether a given integer array is monotonic, meaning the sequence is entirely non-decreasing or entirely non-increasing. This is the sole module for this problem in the repo, following the project's one-solution-per-directory convention.

Key Components

Solution.isMonotonic(self, nums: List[int]) -> bool — The single method. It takes a list of integers and returns True if the array is monotonically non-decreasing, monotonically non-increasing, or both (i.e., all elements equal).

The method uses two boolean flags:

The final return is increasing or decreasing. If either flag survived the full scan, the array is monotonic.

Patterns

Dual-flag single-pass scan. Rather than making two passes (one checking non-decreasing, one checking non-increasing) or sorting/comparing, this tracks both properties simultaneously in O(n) time and O(1) space. Each adjacent pair can only falsify one of the two flags, so the flags are independently flipped. This is the canonical approach for this problem.

LeetCode Solution class convention. The method lives on a Solution class with no _init_, matching the LeetCode submission interface that the test harness instantiates.

Dependencies

Imports: typing.List — used only for the type annotation on nums.

Imported by: monotonic-array/test_solution.py directly. The massive "Imported By" list in the prompt is an artifact of the repo's shared test infrastructure, not actual imports of this module — each test file imports its own Solution from its sibling solution.py.

Flow

1. Initialize increasing = True, decreasing = True.

2. Iterate i from 0 to len(nums) - 2.

3. For each adjacent pair (nums[i], nums[i+1]):

4. Return increasing or decreasing.

For a constant array like [3, 3, 3], neither condition fires, so both flags remain True — correctly returns True.

Invariants

Error Handling

None. The method assumes valid input per the LeetCode contract (a list of integers with 1 <= len(nums) <= 10^5). No bounds checking, no exception handling, no edge-case guards beyond the natural behavior of range(0) for single-element inputs.