Learn a one-pass way to check if array is sorted in non-decreasing order. Intuition, commented Python code, dry run, and clear Big-O analysis included.
So let’s get started with the [Problem Link].
Contents:
[show]
1. What does the problem ask?
Given an integer array arr
, decide if it is sorted in non-decreasing order (each element is no larger than the next).
Return True
if the whole array obeys this rule, otherwise return False
.
2. Quick examples
arr | Output | Why |
---|---|---|
[1, 2, 2, 5] | True | Every element ≤ the next one. |
[3, 4, 1] | False | 4 > 1 breaks the rule. |
[7] | True | A single element is always sorted. |
[] | True | An empty list is trivially sorted. |
3. Intuition & approach
- Sliding window of size 2 – look at every neighbour pair
arr[i]
andarr[i + 1]
. - The array is sorted only if all pairs satisfy
arr[i] ≤ arr[i+1]
. - The first pair that violates this instantly proves the array is not sorted, so we can stop early.
Think of walking from left to right; the moment you step down a hill, you know the landscape is not purely uphill.
4. Code
class Solution:
def arraySortedOrNot(self, arr) -> bool:
n = len(arr)
# Scan pairs (i, i+1)
for i in range(n - 1): # last index is n-2
if arr[i] > arr[i + 1]: # found a drop
return False
return True # never dropped → sorted
5. Step-by-step explanation
- Length check – no special case needed; the loop runs
0
times whenn ≤ 1
, returningTrue
. - Loop from index
0
ton − 2
.- Compare current element with the next.
- If ever
arr[i] > arr[i+1]
, immediately returnFalse
(unsorted).
- If the loop finishes without early exit, every pair was in order → return
True
.
6. Dry run on [3, 5, 5, 2, 6]
i | Compare | Result |
---|---|---|
0 | 3 ≤ 5 | OK |
1 | 5 ≤ 5 | OK |
2 | 5 ≤ 2 | False → exit |
The function returns False
after meeting the first violation.
7. Complexity
Metric | Value | Reason |
---|---|---|
Time | O(n) | Single pass over the array. |
Space | O(1) | Only a few counters; no extra data structures. |
8. Conclusion
To check if an array is sorted, you only need to compare each element with its neighbour once. This linear scan is:
- Simple – five short lines of code.
- Efficient – runs in
O(n)
time andO(1)
space. - Early-exit capable – stops the moment an out-of-order pair appears.
A perfect example where the straightforward approach is already optimal.