Tutorialspoint
Problem
Solution
Submissions

Check if a List is Sorted

Certification: Basic Level Accuracy: 42.37% Submissions: 59 Points: 5

Write a Python program that determines whether a given list of numbers is sorted in ascending order.

Example 1
  • Input: list = [1, 2, 3, 4, 5]
  • Output: True
  • Explanation:
    • Step 1: Compare each adjacent pair of elements starting from the first element.
    • Step 2: Check if element[i] <= element[i+1] for all indices i from 0 to n-2.
    • Step 3: Since all adjacent elements satisfy this condition, the list is sorted.
    • Step 4: Return True.
Example 2
  • Input: list = [1, 3, 2, 4, 5]
  • Output: False
  • Explanation:
    • Step 1: Compare each adjacent pair of elements starting from the first element.
    • Step 2: When checking elements at index 1 and 2, we find 3 > 2.
    • Step 3: Since this violates the ascending order condition, the list is not sorted.
    • Step 4: Return False.
Constraints
  • 0 ≤ len(list) ≤ 10^6
  • List elements are integers
  • Time Complexity: O(n) where n is the length of the list
  • Space Complexity: O(1) as no additional space is needed
StringsListFacebookGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Compare adjacent elements: all(nums[i] <= nums[i+1] for i in range(len(nums)-1))
  • Create a sorted copy and compare: sorted(nums) == nums
  • Use a loop to check each element against the next one

Steps to solve by this approach:

 Step 1: Handle edge cases - empty lists or single-element lists are always considered sorted.

 Step 2: Iterate through the list up to the second-to-last element.
 Step 3: Compare each element with the next element in the list.
 Step 4: If any element is greater than the next element, the list is not sorted.
 Step 5: If we complete the iteration without finding any out-of-order elements, return True.

Submitted Code :