C++ 0896.cpp
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
int sign = 1;
if (nums.back() - nums.front() < 0)
sign = -1;
for (size_t i = 1; i < nums.size(); i++)
if ((nums[i] - nums[i - 1]) * sign < 0)
return false;
return true;
}
};
Difficulty
and has an acceptance rate of about 62% (900k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation determines whether a sequence of integers is monotonic, meaning it is either entirely non-increasing or non-decreasing. It does this by first establishing the overall direction of the sequence based on the first and last elements, then iterating through adjacent pairs to verify that each step conforms to the identified direction. The function returns true when all steps are consistent with the direction and false otherwise.
Key Steps
Establishing the Expected Direction
The algorithm begins by assuming an increasing direction (sign = 1). It then compares the last element with the first element; if the difference is negative, the expected direction is reversed by setting sign to -1. This single comparison captures the overall trend of the array without needing to examine every element.
int sign = 1;
if (nums.back() - nums.front() < 0)
sign = -1;
Verifying Consistency of Adjacent Differences
A forward loop starts at the second element and proceeds to the end of the vector. For each pair of consecutive elements, the difference is multiplied by the previously determined sign. If the product is negative, the current step contradicts the expected monotonic direction, and the function returns false immediately.
for (size_t i = 1; i < nums.size(); i++)
if ((nums[i] - nums[i - 1]) * sign < 0)
return false;
Concluding the Check
If the loop completes without encountering a contradictory step, the sequence satisfies the monotonic condition, and the function returns true.
return true;
Edge Cases Handled
When the input vector contains a single element, the initial direction calculation uses the same element for both front() and back(), resulting in a zero difference and leaving sign as 1. The loop body never executes because the range 1 to size() is empty, so the function returns true. This correctly treats a single-element sequence as monotonic.
If all elements are equal, the difference between any adjacent pair is zero. Multiplying zero by either 1 or -1 yields zero, which is not less than zero, so the loop never triggers a false return. The function therefore identifies a constant sequence as monotonic in both directions.
For strictly decreasing sequences, the initial comparison yields a negative difference, setting sign to -1. Each subsequent adjacent difference is also negative, and the product of two negatives is positive, never satisfying the < 0 condition. The loop therefore completes successfully, confirming the decreasing monotonicity.
Conversely, for strictly increasing sequences, sign remains 1. Each adjacent difference is positive, and the product remains positive, again avoiding the early exit condition and resulting in a true outcome.
Performance Optimizations
The algorithm achieves early termination by returning false at the first detection of a direction violation. This prevents unnecessary processing of the remainder of the vector once a non-monotonic step is found.
The use of a single sign variable eliminates the need for separate branches or multiple conditional checks for increasing and decreasing cases. By converting the direction into a multiplier, the code reduces each iteration to a single arithmetic operation and a comparison, streamlining the inner loop.
Employing size_t for the loop index aligns with the type returned by vector::size(), avoiding implicit conversions and potential signed-unsigned mismatches that could incur extra checks.
The subtraction of adjacent elements (nums[i] - nums[i - 1]) is performed directly without invoking any helper functions, keeping the operation inlined and cache-friendly. The overall structure ensures linear traversal with minimal overhead per element.
ELI5 - Simplified Explanation
Imagine you have a long line of numbered building blocks. You want to see if the blocks are arranged in a special way where they keep getting bigger or keep getting smaller, without ever changing their minds.
First, the code looks at the very first block and the very last block in your line. It checks which one is bigger to decide if the line is supposed to be growing like a mountain or shrinking like a slide. The variable called sign remembers this secret plan.
After deciding the plan, the code walks down the line from the start to the end. It looks at each block and the one that came just before it. It does a little bit of math to see if the current block follows the plan. If the code ever finds a spot where a block goes the wrong way, it knows the line is not perfectly sorted, so it says that the line is not monotonic. If it finishes the whole walk without finding any mistakes, the line is exactly how it should be.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality