Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether list is strictly increasing or strictly decreasing in Python
Suppose we have a list of numbers; we have to check whether the list is strictly increasing or strictly decreasing. A list is strictly increasing if each element is larger than the previous one, and strictly decreasing if each element is smaller than the previous one.
So, if the input is like nums = [10, 12, 23, 34, 55], then the output will be True, as all elements are distinct and each element is larger than the previous one, so this is strictly increasing.
Algorithm
To solve this, we will follow these steps ?
- If size of nums <= 2, then return True (trivially strictly ordered)
- If all elements in nums are not distinct, then return False
- Create a sorted version of the list
- Return True when nums is same as sorted list or nums is same as sorted list in reverse order, otherwise False
Implementation
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, nums):
if len(nums) <= 2:
return True
if len(set(nums)) != len(nums):
return False
ordered = sorted(nums)
return nums == ordered or nums == ordered[::-1]
ob = Solution()
print(ob.solve([10, 12, 23, 34, 55]))
print(ob.solve([55, 34, 23, 12, 10]))
print(ob.solve([10, 20, 15, 30]))
print(ob.solve([5, 5, 6]))
True True False False
Alternative Approach Using Direct Comparison
We can also check directly by comparing adjacent elements ?
def is_strictly_ordered(nums):
if len(nums) <= 2:
return True
# Check if strictly increasing
increasing = all(nums[i] < nums[i + 1] for i in range(len(nums) - 1))
# Check if strictly decreasing
decreasing = all(nums[i] > nums[i + 1] for i in range(len(nums) - 1))
return increasing or decreasing
# Test cases
test_cases = [
[10, 12, 23, 34, 55], # Strictly increasing
[55, 34, 23, 12, 10], # Strictly decreasing
[10, 20, 15, 30], # Neither
[5, 5, 6], # Not strict (duplicate)
[1, 2] # Trivial case
]
for case in test_cases:
print(f"{case} ? {is_strictly_ordered(case)}")
[10, 12, 23, 34, 55] ? True [55, 34, 23, 12, 10] ? True [10, 20, 15, 30] ? False [5, 5, 6] ? False [1, 2] ? True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Sorting approach | O(n log n) | O(n) | Simple logic |
| Direct comparison | O(n) | O(1) | Better performance |
Conclusion
Both approaches work effectively to check if a list is strictly increasing or decreasing. The direct comparison method is more efficient with O(n) time complexity, while the sorting approach offers cleaner logic but requires O(n log n) time.
