Skip to content

Create monotonic_array.py #11025

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 27, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions data_structures/arrays/monotonic_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# https://leetcode.com/problems/monotonic-array/
def is_monotonic(nums: list[int]) -> bool:
"""
Check if a list is monotonic.

>>> is_monotonic([1, 2, 2, 3])
True
>>> is_monotonic([6, 5, 4, 4])
True
>>> is_monotonic([1, 3, 2])
False
"""
return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all(
nums[i] >= nums[i + 1] for i in range(len(nums) - 1)
)


# Test the function with your examples
print(is_monotonic([1, 2, 2, 3])) # Output: True
print(is_monotonic([6, 5, 4, 4])) # Output: True
print(is_monotonic([1, 3, 2])) # Output: False
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please encapsulate all driver code within an if __name__ == "__main__" block