Check if an Array Is Sorted
You get an array of integers nums. Return true if it is in non-decreasing order, meaning every element is less than or equal to the one after it, and false otherwise. Equal neighbours are fine: [2, 2, 3] counts as sorted. An array with one element is sorted.
Function
- numsinteger-array
- the array of integers to check
- Returnsboolean
- true when every element is at most the next one, false otherwise
Constraints
1 ≤ nums.length ≤ 5000-109 ≤ nums[i] ≤ 109
Examples
- Input
- nums = [1, 3, 3, 7]
- Output
- true
- Explanation
- Each step goes up or stays level: 1 to 3, 3 to 3, 3 to 7. The repeated 3 is allowed, so the answer is
true.
- Input
- nums = [2, 5, 4, 9]
- Output
- false
- Explanation
- The step from 5 to 4 goes down, and one such step makes the array unsorted, even though 9 at the end is the largest value.
Follow-up
How would you check an array that may be sorted in either direction, increasing or decreasing, still in one pass?
Hints
Open them one at a time. Each one gives away a little more.
If an array is not sorted, where in it can you see that? Do you need to compare elements that are far apart?
It is enough to compare each element with the one right after it. Equal neighbours are allowed; only a step down breaks the order.
Loop over the neighbouring pairs and return
falseat the first pair where the left value is greater than the right one. If no such pair exists, returntrue.
Solution
An array is sorted exactly when no element is larger than the one right after it. So one pass over the n-1 neighbouring pairs decides it, and the pass can stop at the first step down.
Sort a copy and compare
Intuition
A sorted array is the one that sorting would not change: sort a copy and compare it with nums position by position. For [2, 5, 4, 9] the copy [2, 4, 5, 9] differs at position 1, so the answer is false.
Sorting costs O(n log n), about 6 × 10^4 comparisons for 5000 numbers, plus O(n) memory for the copy, and it reads the whole array even when the first pair is already out of order.
Algorithm
- Copy
numsso the original stays unchanged. - Sort the copy in increasing numeric order.
- Compare the copy with
numsposition by position. - Return
trueif every position matches,falseotherwise.
def isSorted(nums):
# sorted returns a new list, so nums itself is left as it was.
return sorted(nums) == numsCompare each pair of neighbours
Intuition
Because ≤ chains (a ≤ b and b ≤ c give a ≤ c), the n-1 neighbouring pairs cover every pair of positions, and an unsorted array always has a neighbouring pair that goes down. So walk i from 1 to n-1 and return false at the first nums[i-1] > nums[i]. For [2, 5, 4, 9] that is the pair (5, 4), and 9 is never read. Equal neighbours pass, because only > fails.
Each pair is compared once: O(n) time and O(1) memory.
Algorithm
- Loop
ifrom 1 ton-1. - If
nums[i-1] > nums[i], returnfalse. - If the loop finishes, return
true. A single element skips the loop and is sorted.
def isSorted(nums):
for i in range(1, len(nums)):
# One step down anywhere breaks the order.
if nums[i - 1] > nums[i]:
return False
return True
Pitfalls and edge cases
- Treating equal neighbours as a failure. Testing
nums[i-1] >= nums[i]rejects[1, 3, 3, 7]. - Reading past the end. A loop from
0ton-1that comparesnums[i]withnums[i+1]reads outside the array on its last step. Start ati = 1and compare withi-1. - Subtracting instead of comparing.
nums[i] - nums[i-1] >= 0overflows a 32-bit int on[-1000000000, 1000000000]:2 × 10^9wraps negative and the array is reported unsorted. A qsort comparator written asx - ybreaks the same way. - Sorting numbers as text. In JavaScript,
sort()with no compare function puts10before9, so sort-and-compare gives wrong answers.
Frequently asked questions3
How do you check if an array is sorted?
Compare each element with the next one. If any element is greater than its right neighbour, the array is not sorted and you can stop; if you reach the end without finding one, it is. That takes O(n) time and O(1) extra space.
Is an array with equal elements sorted?
In non-decreasing order, yes: [4, 4, 4] is sorted because no element is larger than the next. If a problem asks for strictly increasing order instead, change the test to reject equal neighbours as well.
Can I sort a copy and compare it with the original?
Yes, it gives the right answer, but it costs O(n log n) time and O(n) extra memory. The neighbour check needs no copy and can stop at the first step down.
Similar problems
Problems that use the same ideas. Solving two or three of them is what makes a pattern stick.
def isSorted(nums):
# Write code hereTest #1
Test #2
Argument
nums = [1, 3, 3, 7]
Expected Output
true