-
Notifications
You must be signed in to change notification settings - Fork 243
Is Monotonic
Sar Champagne Bielert edited this page Apr 7, 2024
·
6 revisions
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Do I need to return anything different to distinguish between an increasing and decreasing array?
- No. In both cases, your function should return
True
.
- No. In both cases, your function should return
- What if the array is empty?
- In this case, return True.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Loop through each element in the list, and keep track of whether it consistently increases or descreases.
1) By default, assume the array is both increasing AND decreasing
2) Loop through each index in the array, starting at index 1
a) Compare the current value to the previous value
i) If previous < current, decreasing must be False
ii) If previous > current, increasing must be False
3) If either increasing or decreasing is still True, return True
- Since you need to check the previous/next element (depending on how you write your solution), make sure your loop doesn't go out of bounds!
def is_monotonic(nums):
increasing = decreasing = True
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
decreasing = False
elif nums[i] < nums[i-1]:
increasing = False
return increasing or decreasing
*Note: You could potentially give this function a better best-case & average-case efficiency by exiting the loop early when both decreasing
and increasing
are false.
However, this won't effect the worst-case efficiency (Big-O) of the solution.*