896. Monotonic Array LeetCode Solution

In this guide, you will get 896. Monotonic Array LeetCode Solution with the best time and space complexity. The solution to Monotonic Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Monotonic Array solution in C++
  4. Monotonic Array solution in Java
  5. Monotonic Array solution in Python
  6. Additional Resources
896. Monotonic Array LeetCode Solution image

Problem Statement of Monotonic Array

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 = nums[j].
Given an integer array nums, return true if the given array is monotonic, or false otherwise.

Example 1:

Input: nums = [1,2,2,3]
Output: true

Example 2:

Input: nums = [6,5,4,4]
Output: true

Example 3:

Input: nums = [1,3,2]
Output: false

Constraints:

1 <= nums.length <= 105
-105 <= nums[i] <= 105

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

896. Monotonic Array LeetCode Solution in C++

class Solution {
 public:
  bool isMonotonic(vector<int>& nums) {
    bool increasing = true;
    bool decreasing = true;

    for (int i = 1; i < nums.size(); ++i) {
      increasing &= nums[i] >= nums[i - 1];
      decreasing &= nums[i] <= nums[i - 1];
    }

    return increasing || decreasing;
  }
};
/* code provided by PROGIEZ */

896. Monotonic Array LeetCode Solution in Java

class Solution {
  public boolean isMonotonic(int[] nums) {
    boolean increasing = true;
    boolean decreasing = true;

    for (int i = 1; i < nums.length; ++i) {
      increasing &= nums[i] >= nums[i - 1];
      decreasing &= nums[i] <= nums[i - 1];
    }

    return increasing || decreasing;
  }
}
// code provided by PROGIEZ

896. Monotonic Array LeetCode Solution in Python

class Solution:
  def isMonotonic(self, nums: list[int]) -> bool:
    increasing = True
    decreasing = True

    for i in range(1, len(nums)):
      increasing &= nums[i - 1] <= nums[i]
      decreasing &= nums[i - 1] >= nums[i]

    return increasing or decreasing
# code by PROGIEZ

Additional Resources

See also  99. Recover Binary Search Tree LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.