Determine If an Array Is Already Sorted

Solve this Problem
Easy5–10 min
Topics
Companies
Practice:GFG ↗
Given an array of integers nums, determine whether it is sorted in non-decreasing order — meaning every element is greater than or equal to the one before it. You don't need to sort the array or return anything about *how* it's ordered — just answer true or false. Equal neighbouring values are allowed; only a strictly-smaller element right after a bigger one breaks the order.

Test Case 1:

Input:nums = [2, 4, 6, 6, 9, 15]
Output:true
Explanation:Every element is greater than or equal to the one before it.

Test Case 2:

Input:nums = [8, 3, 12]
Output:false
Explanation:3 comes right after 8 but is smaller, which breaks the non-decreasing order.

Test Case 3:

Input:nums = [7, 7, 7, 7]
Output:true
Explanation:Equal neighbours are fine — non-decreasing order allows repeated values.

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

🧪Try your own test case
1class Solution {
2 public boolean isSorted(int[] nums) {
3 for (int i = 1; i < nums.length; i++) {
4 if (nums[i] < nums[i - 1]) {
5 return false;
6 }
7 }
8 return true;
9 }
10}
11
2
4
3
6
9
0
1
2
3
4
i
Variables
i1
nums[i]4
nums[i-1]2
SELECT

Compare nums[1] = 4 with the element right before it, nums[0] = 2.

Step 1 / 5

Approach & Solutions

Brute Force — Sort and Compare

Brute

Make a sorted copy of the array. If the original array is identical, element by element, to its sorted copy, it was already sorted. Correct, but sorting is far more work than this check actually needs.

TimeO(n log n)
SpaceO(n)
1class Solution { 2 public boolean isSorted(int[] nums) { 3 int[] sorted = nums.clone(); 4 Arrays.sort(sorted); 5 return Arrays.equals(nums, sorted); 6 } 7}

Optimal — Single Pass

Optimal

Walk the array once, comparing every element to the one right before it. The moment an element is smaller than its predecessor, the array can't be non-decreasing — stop and report false. If the whole walk finishes without finding such a pair, the array is sorted.

TimeO(n)
SpaceO(1)
1class Solution { 2 public boolean isSorted(int[] nums) { 3 for (int i = 1; i < nums.length; i++) { 4 if (nums[i] < nums[i - 1]) { 5 return false; 6 } 7 } 8 return true; 9 } 10}

Related Problems