AlgoMaster Logo

Check if an Array is Sorted

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

Decide whether the array is in non-decreasing order, meaning every element is less than or equal to the one right after it. As soon as one value drops, the whole array fails the test.

"Non-decreasing" is not "strictly increasing." Equal neighbors are fine. [1, 2, 2, 3] is sorted because no element is larger than the one after it, even though two are equal. Only a strict drop, where some nums[i] is greater than nums[i + 1], breaks the order.

Empty arrays and single-element arrays have no adjacent pair to compare, so both count as sorted by definition.

Key Constraints:

  • Non-decreasing order → Each element must be <= the next one. Equal adjacent values such as the two 2s in [1, 2, 2, 3] are allowed, so the check should reject only a strict drop where nums[i] > nums[i + 1].
  • Empty or single element → An array of length 0 or 1 has no adjacent pair, so it is trivially sorted and should return true.
  • -2^31 <= nums[i] <= 2^31 - 1 → Values can be negative, so the comparison must work across the full signed range rather than assuming positive numbers.

Approach 1: Adjacent Comparison

Intuition

Walk through the array once and check each nums[i] against nums[i + 1]. If you find a pair where nums[i] > nums[i + 1], the order is broken, so return false right away. One violation disqualifies the array, so there is no reason to keep scanning. If you reach the end without one, every neighbor was in order, so return true.

This single pass avoids sorting a copy or comparing distant elements.

Algorithm

  1. Loop i from 0 to nums.length - 2, covering every adjacent pair.
  2. If nums[i] > nums[i + 1], return false immediately.
  3. If the loop finishes without finding a violation, return true.
  4. An empty or single-element array never enters the loop body, so it returns true.

Example Walkthrough

Input:

0
1
1
2
2
2
3
3
nums

Compare the pairs from left to right. First, nums[0] = 1 against nums[1] = 2. Since 1 <= 2, the order holds. Next, nums[1] = 2 against nums[2] = 2. Since 2 <= 2, the equal pair is allowed and the order still holds. Then nums[2] = 2 against nums[3] = 3. Since 2 <= 3, that holds too. The loop reaches the end with no violation, so the result is true.

true
result

Code