Skip to content

Commit

Permalink
add solution isMonotonic python
Browse files Browse the repository at this point in the history
  • Loading branch information
ragmha committed May 4, 2024
1 parent 0f3f4c1 commit 8bc2686
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

| Name | Tags | Solution |
| --------------------------------------------------------- | ----------------------- | ----------------------------------------------------------------------- |
| Is-Monotonic | `Arrays` | [TypeScript](./src/algorithms/arrays/is-monotonic) |
| Is-Monotonic | `Arrays` | [TypeScript](./src/algorithms/arrays/is-monotonic/is-monotonic.ts) , [Python](./src/algorithms/arrays/is-montonic/is_monotonic.py) |
| 2D Array - DS | `Arrays` | [TypeScript](./src/algorithms/arrays/2d-array-ds) |
| Left Rotation | `Arrays` | [TypeScript](./src/algorithms/arrays/left-rotation) |
| New Year Chaos | `Arrays` | [TypeScript](./src/algorithms/arrays/new-year-chaos) |
Expand Down
26 changes: 26 additions & 0 deletions src/algorithms/arrays/is-monotonic/is_monotonic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""
Is Monotonic
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j].
An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].
Given an integer array nums, return true if the given array is monotonic, or false otherwise.
"""

from typing import List


class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
if nums[-1] - nums[0] < 0:
nums.reverse()

for i in range(len(nums) - 1):
if not (nums[i] <= nums[i + 1]):
return False

return True
19 changes: 19 additions & 0 deletions src/algorithms/arrays/is-monotonic/test_is_monotonic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import unittest
from is_monotonic import Solution


class TestIsMonotonic(unittest.TestCase):

def setUp(self):
self.solution = Solution()

def test_isMonotonic(self):
self.assertTrue(self.solution.isMonotonic([1, 2, 2, 3]))

self.assertTrue(self.solution.isMonotonic([6, 5, 4, 4]))

self.assertFalse(self.solution.isMonotonic([1, 3, 2]))


if __name__ == '__main__':
unittest.main()

0 comments on commit 8bc2686

Please sign in to comment.