Check if the Array is Sorted I
Pattern: Traversal and in-place tricks
An array is sorted when no element is smaller than the one before it, so compare each neighbouring pair once.
The problem
You are given an array of between 1 and 100,000 whole numbers. Return true if it is sorted in non-decreasing order (each
element is at least the one before it, so equal neighbours are fine), and false otherwise. For example, [1, 2, 2, 5] is
sorted and [1, 3, 3, 2] is not.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name isSorted and the limits are this guide's own.
Think first
- Do you need to sort the array to know whether it is sorted?
- Which pairs of elements must you compare? All pairs, or only some?
- Is
[4, 4, 4]sorted under this problem's rule?
Hints
Brute force, and why it fails
Sort a copy and compare it with the original: O(n log n) time and O(n) extra memory. Comparing every pair i < j is
O(n²). Neighbouring pairs are enough, because "sorted" is a chain: if each link is in order, so is the whole chain.
The key insight
Order is a local property: an array is sorted exactly when every neighbouring pair is in order. One pass of n - 1
comparisons decides it.
Dry run
| i | 1 |
|---|
nums = [1, 3, 3, 2]. Compare each element with the one before it, starting at index 1.
The plan
for i from 1 to n - 1:
if nums[i] < nums[i - 1]:
return false # a step down
return true
Complexity
- Time
O(n)- Space
O(1)
At most n - 1 comparisons, and no extra memory.
Edge cases
- One element is sorted. The loop does not run.
- Equal values such as
[4, 4, 4]are sorted. - A step down at the very end, such as
[1, 2, 3, 0], must still be caught.
I've built my logic, show the code
Java
class Solution {
public boolean isSorted(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) { // a step down breaks the order
return false;
}
}
return true;
}
}C++
class Solution {
public:
bool isSorted(vector<int>& nums) {
for (int i = 1; i < static_cast<int>(nums.size()); i++) {
if (nums[i] < nums[i - 1]) { // a step down breaks the order
return false;
}
}
return true;
}
};Python
class Solution:
def isSorted(self, nums):
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]: # a step down breaks the order
return False
return TrueCommon mistakes
- Using
<=in the test, which wrongly rejects equal neighbours. - Starting at
i = 0and readingnums[-1]. - Returning true as soon as one pair is in order.