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.
isSorted([1, 2, 3])
# TrueisSorted([1, 2, 2, 3])
# TrueisSorted([1, 3, 2])
# FalseTo 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:
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 TrueThis 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:
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 TrueTime Complexity 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). We don't have to store any variables in memory, so the space is just O(1).