Skip to main content

Check if Array is Sorted

Problem Statement:โ€‹

Given an arrayย arr[], check whether it is sorted inย non-decreasingย order. Returnย trueย if it is sorted otherwiseย false.

  • Example:

    Examples:

    Input: arr[] = [10, 20, 30, 40, 50]
    Output: true
    Explanation: The given array is sorted.
    Input: arr[] = [90, 80, 100, 70, 40, 30]
    Output: false
    Explanation: The given array is not sorted.

โœ… Solution: Brute Force โ€“ Single Passโ€‹

class Solution {
public:
bool isSorted(vector<int>& arr) {
// Traverse the array from index 1 to end
for(int i = 1; i < arr.size(); i++){
// If any previous element is greater, it's not sorted
if(arr[i - 1] > arr[i]){
return false;
}
}
// If no such pair is found, the array is sorted
return true;
}
};


๐Ÿ“ How It Worksโ€‹

  • The function iterates from the second element to the last.
  • For each element, it compares it with its previous one.
  • If at any point the current element is less than the previous one, it returns false (not sorted in non-decreasing order).
  • If the loop completes without finding such a pair, it returns true.

๐Ÿงฉ Key Formula / Recurrenceโ€‹

  • Thereโ€™s no recurrence โ€“ just a linear scan with the check:

    if arr[i-1] > arr[i] โ†’ not sorted


โฑ๏ธ Time & Space Complexityโ€‹

ComplexityValue
TimeO(N)
SpaceO(1)

โš ๏ธ Edge Casesโ€‹

  • Empty array [] โ†’ considered sorted โœ…
  • Single-element array [42] โ†’ sorted โœ…
  • All elements equal [3, 3, 3] โ†’ sorted โœ…
  • Strictly decreasing [5, 4, 3] โ†’ not sorted โŒ

๐Ÿ’ก Other Approachesโ€‹

ApproachTimeNotes
STL is_sorted()O(N)Use return is_sorted(arr.begin(), arr.end()); for cleaner code
Compare to sorted copyO(N log N)Make a sorted version and compare โ€“ inefficient for this task โŒ

  • Check if array is strictly increasing
  • Count the number of unsorted pairs in an array
  • Sort an array using minimum swaps

๐Ÿ› ๏ธ Other Notesโ€‹

  • This is an ideal use-case for a simple scan, no need for recursion or extra space.
  • This is stable for arrays with duplicates and works well for real-time checks like verifying if logs, scores, or timestamps are in order.
๐Ÿš€ Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Serverโ†’
โšก
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

๐Ÿ’กHave handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contributeโ†’