Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Check if array is sorted | Explained using Python Code
    Data Structures & Algorithms

    Check if array is sorted | Explained using Python Code

    codeanddebugBy codeanddebug13 June 2025No Comments2 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Check if the array is sorted or not featured image
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Learn a one-pass way to check if array is sorted in non-decreasing order. Intuition, commented Python code, dry run, and clear Big-O analysis included.

    So let’s get started with the [Problem Link].

    Contents:
     [show]
    • 1. What does the problem ask?
    • 2. Quick examples
    • 3. Intuition & approach
    • 4. Code
    • 5. Step-by-step explanation
    • 6. Dry run on [3, 5, 5, 2, 6]
    • 7. Complexity
    • 8. Conclusion

    1. What does the problem ask?

    Given an integer array arr, decide if it is sorted in non-decreasing order (each element is no larger than the next).
    Return True if the whole array obeys this rule, otherwise return False.


    2. Quick examples

    arrOutputWhy
    [1, 2, 2, 5]TrueEvery element ≤ the next one.
    [3, 4, 1]False4 > 1 breaks the rule.
    [7]TrueA single element is always sorted.
    []TrueAn empty list is trivially sorted.

    3. Intuition & approach

    1. Sliding window of size 2 – look at every neighbour pair arr[i] and arr[i + 1].
    2. The array is sorted only if all pairs satisfy arr[i] ≤ arr[i+1].
    3. The first pair that violates this instantly proves the array is not sorted, so we can stop early.

    Think of walking from left to right; the moment you step down a hill, you know the landscape is not purely uphill.


    4. Code

    class Solution:
        def arraySortedOrNot(self, arr) -> bool:
            n = len(arr)
            # Scan pairs (i, i+1)
            for i in range(n - 1):           # last index is n-2
                if arr[i] > arr[i + 1]:      # found a drop
                    return False
            return True                      # never dropped → sorted

    5. Step-by-step explanation

    1. Length check – no special case needed; the loop runs 0 times when n ≤ 1, returning True.
    2. Loop from index 0 to n − 2.
      • Compare current element with the next.
      • If ever arr[i] > arr[i+1], immediately return False (unsorted).
    3. If the loop finishes without early exit, every pair was in order → return True.

    6. Dry run on [3, 5, 5, 2, 6]

    iCompareResult
    03 ≤ 5OK
    15 ≤ 5OK
    25 ≤ 2False → exit

    The function returns False after meeting the first violation.


    7. Complexity

    MetricValueReason
    TimeO(n)Single pass over the array.
    SpaceO(1)Only a few counters; no extra data structures.

    8. Conclusion

    To check if an array is sorted, you only need to compare each element with its neighbour once. This linear scan is:

    • Simple – five short lines of code.
    • Efficient – runs in O(n) time and O(1) space.
    • Early-exit capable – stops the moment an out-of-order pair appears.

    A perfect example where the straightforward approach is already optimal.

    Array Easy
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleFind the second largest and second smallest element in an Array | Explained
    Next Article Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    13 June 2025
    Data Structures & Algorithms

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025
    Data Structures & Algorithms

    Quick Sort Algorithm in Python | Explained

    13 June 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (49)
      • Beginner (24)
      • Expert (9)
      • Intermediate (16)
    • Uncategorised (1)
    Recent Posts

    Shortest Path in an Undirected Graph with Unit Distance – Clear BFS Solution in Python

    13 June 2025

    Check if array is sorted | Explained using Python Code

    13 June 2025

    Find the second largest and second smallest element in an Array | Explained

    13 June 2025

    Quick Sort Algorithm in Python | Explained

    13 June 2025

    Merge Sort Algorithm in Python | Explained

    13 June 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.