Data Structures

Check Sorted Array

Array

This is a beginner problem, but it's good practice if you're new or rusty.

Given an array of integers arr, return whether the array is sorted in ascending order.

First Few Test Cases:
isSorted([1, 2, 3])
# True
isSorted([1, 2, 2, 3])
# True
isSorted([1, 3, 2])
# False

To solve this problem, you have to check whether the values are in increasing order.

To do this, you can check that each element is greater or equal to the previous element, like this:

Check Sorted Array - image

To write this in code, you can simply loop over the entire array, like this:

def isSorted(arr):
    for i in range(len(arr)):

        # if not greater or equal, return False
        if not arr[i] >= arr[i-1]:
            return False

    # if made it through loop, return True
    return True

This code is mostly correct, but there's a minor issue. When i=0, you run into the case where the previous element doesn't exist, like this:

Check Sorted Array - image

We shouldn't run this case, because our code will break. You can omit this case from the loop, by making the range start at 1, by writing range(1, len(arr)). Here's the solution to the problem:

def isSorted(arr):

    for i in range(1, len(arr)):

        if not arr[i] >= arr[i-1]:
            return False

    return True

Time Complexity O(n)O(n). This algorithm takes O(n) time, because we have to loop over the entire array. The letter "n" refers to the size of the input - in this problem "n" is the length of the array.

Space Complexity O(1)O(1). We don't have to store any variables in memory, so the space is just O(1).

Mark as Completed:
Submits:
isSorted
Test your code to get an output here!
isSorted(
)
Test your code to get an output here!