Explorer
Data Structures & Algorithms

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

  1. Iterate from i = 1 up to arr.length - 1.
  2. If arr[i] < arr[i - 1], an out-of-order pair exists. Return false immediately.
  3. 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.

Check if Array is Sorted

Easy
Given an array of integers, return true if the array is sorted in non-decreasing order, otherwise return false.
Example Scenarios
1Example 1
Input: arr = [1, 2, 2, 3, 3, 4]
Output: true
Explanation:

The array is sorted.

Constraints
•Standard constraints
Editor
Loading Editor...
arr =
[1, 2, 2, 3, 3, 4]
Output:Click "Run" above to execute and verify your code here.
true