Check whether a list is in non-decreasing order by comparing neighbours in O(n), stopping at the first violation. Faster than sorting a copy. Run it live.
The problem
Return True if nums is sorted in non-decreasing order (equal neighbours are fine).
Examples
Example 1
Input
is_sorted([1, 2, 2, 5])
Expected output
True
Example 2
Input
is_sorted([3, 1, 2])
Expected output
False
+ 3 hidden tests on Submit — violation at the end.
Edge cases to ask about
- Empty or single element
- Equal neighbours
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Compare with sorted(nums) | O(n log n) | O(n) | Sorts a full copy to answer a yes/no question. |
| bestCompare neighbours | O(n) | O(1) | Stops at the first out-of-order pair. |
Walkthrough of the optimal approach (try it yourself first)
Compare each element with the one before it and return False at the first drop. nums == sorted(nums) works but sorts a whole copy — O(n log n) time and O(n) space for a yes/no answer.
One-liner: all(a <= b for a, b in zip(nums, nums[1:])).
Complexity: O(n) time, O(1) space. At most n − 1 neighbour comparisons, no copy.
Reveal the reference solution
def is_sorted(nums): for i in range(1, len(nums)): if nums[i] < nums[i - 1]: return False return True
The brute force, for comparison
def is_sorted(nums): return nums == sorted(nums)
Follow-ups interviewers ask
- Strictly increasing instead.
- Sorted in either direction?
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Check If a List Is Sorted in Python?
The optimal solution runs in O(n) time and O(1) auxiliary space. At most n − 1 neighbour comparisons, no copy.
What is the brute-force approach, and how do you optimise it?
Compare with sorted(nums): O(n log n) time, O(n) space. Sorts a full copy to answer a yes/no question. Compare neighbours: O(n) time, O(1) space. Stops at the first out-of-order pair.
What follow-up questions do interviewers ask about Check If a List Is Sorted?
Strictly increasing instead. Sorted in either direction?
