Given an array arr[], tell whether it is sorted in non-decreasing order, meaning every element is greater than or equal to the one before it. Return true if it is, otherwise false.
Check if Array is Sorted
SolvedExamples:
Input: arr[] = [10, 20, 30, 40, 50]
Output: true
Explanation: Each element is at least as large as the previous one.
Input: arr[] = [90, 80, 100, 70]
Output: false
Explanation: 80 comes after 90, so the order is broken.
Constraints:
1 ≤ arr.size() ≤ 10^5-10^9 ≤ arr[i] ≤ 10^9
Expected Complexities
Time Complexity: O(n) Auxiliary Space: O(1)
Company Tags
Topic Tags
Compare each element with its neighbour on the left. The moment you find one that is smaller, the answer is false; if you reach the end without that happening, the array is sorted. Arrays of length one are trivially sorted.
class Solution {
isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) return false;
}
return true;
}
}
Sign in to see your submissions.