Algorithm LogbookAlgorithm Logbook

Sorted Array Check

Array

šŸ“‹ 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: ai≤ai+1a_i \leq a_{i+1} for all ii. 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

  1. Iterate through indices 00 to Nāˆ’2N-2 (using range(len(arr) - 1)).
  2. At each position, compare arr[i] with arr[i+1].
  3. If arr[i] > arr[i+1], the array is not sorted — return False immediately.
  4. If the loop completes without finding any violations, return True.

⚔ Complexity Analysis

Time

O(N)O(N) in the worst case (fully sorted array), but can exit early in practice

Space

O(1)O(1) — only loop variables are used

āš ļø Common Mistakes

  • Using range(len(arr)) instead of range(len(arr) - 1), causing an index-out-of-bounds error when accessing arr[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 O(1)O(1) time. This "fail fast" approach appears frequently in validation problems.