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โ
| Complexity | Value |
|---|---|
| Time | O(N) |
| Space | O(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โ
| Approach | Time | Notes |
|---|---|---|
STL is_sorted() | O(N) | Use return is_sorted(arr.begin(), arr.end()); for cleaner code |
| Compare to sorted copy | O(N log N) | Make a sorted version and compare โ inefficient for this task โ |
๐ Related Problemsโ
- 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.
Official Hub
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.