Check if an Array Is Sorted

Problem

Check whether an array is sorted in non-decreasing order.

Input:  nums = [1, 2, 2, 4, 5]
Output: true

Input:  nums = [3, 1, 2]
Output: false

Python Solution

def is_sorted(nums):
    for i in range(1, len(nums)):
        if nums[i] < nums[i - 1]:
            return False
    return True

C++ Solution

bool isSorted(vector<int>& nums) {
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] < nums[i - 1]) return false;
    }
    return true;
}

Java Solution

class Solution {
    public boolean isSorted(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < nums[i - 1]) return false;
        }
        return true;
    }
}

Complexity

Time: O(n) — checks each adjacent pair once, and returns early on the first violation. Space: O(1) — no extra data structure used.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.