Check if an array is sorted in non-decreasing order.
Problem Statement
Given an array of integers, return true if the array is sorted in non-decreasing order, otherwise return false.
Examples
Input: arr = [1, 2, 2, 3, 3, 4]
Output: true
Explanation: The array is sorted.
Constraints
Standard constraints
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
An array is sorted if every element arr[i] >= arr[i - 1].
š” Hint 2:
Iterate through the array from index 1. If at any point arr[i] < arr[i-1], return false.
š” Hint 3:
If the loop completes without finding any inversion, return true.
Editorial & Approach
Problem Overview & Intuition
A sorted array in non-decreasing order satisfies the condition that each element is greater than or equal to its predecessor. A single scan checking adjacent pairs determines correctness in O(N) time.
Step-by-Step Approach
- Iterate from
i = 1up toarr.length - 1. - If
arr[i] < arr[i - 1], an out-of-order pair exists. Returnfalseimmediately. - If the loop completes with no violations, return
true.
Optimal Implementation (JavaScript)
function isSorted(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
Complexity Analysis
Time Complexity
O(N) ā single pass with early exit on first inversion.
Space Complexity
O(1) ā no extra memory allocated.
Edge Cases & Corner Traps Handled
- Array of length 0 or 1: always sorted (returns true).
- Array with all identical elements: non-decreasing, returns true.
- Strictly descending array: returns false on index 1.