Sorted Array Check
š Problem Statement
Write a function that returns True if an array is sorted in ascending order, and False otherwise. For example, [1, 2, 3, 4, 5] returns True, while [1, 2, 3, 5, 4] returns False.
š” Intuition
A sorted array has the property that every element is less than or equal to the next one: for all . We only need to find a single violation to prove the array is unsorted. This is the "early exit" pattern ā return False immediately upon finding the first violation.
š§ Approach
- Iterate through indices to (using
range(len(arr) - 1)). - At each position, compare
arr[i]witharr[i+1]. - If
arr[i] > arr[i+1], the array is not sorted ā return False immediately. - If the loop completes without finding any violations, return True.
ā” Complexity Analysis
in the worst case (fully sorted array), but can exit early in practice
ā only loop variables are used
ā ļø Common Mistakes
- Using
range(len(arr))instead ofrange(len(arr) - 1), causing an index-out-of-bounds error when accessingarr[i+1] - Not handling edge cases: an empty array
[]or single-element array[5]should both return True - Checking strict less-than (
<) instead of less-than-or-equal (<=), incorrectly marking[1, 1, 2]as unsorted
šÆ Final Thoughts
The early exit pattern is a powerful optimization. In the best case, you find a violation at the very first pair and return in time. This "fail fast" approach appears frequently in validation problems.