What is Monotonic Arrays – Algorithm to check if an array is Monotonic

Monotonic arrays are a fundamental concept in computer science and data structures. They are essential for a wide range of applications, such as searching and sorting algorithms. In this blog post, we’ll explore two different approaches to check if an array is monotonic: the brute-force method and an optimized single-pass solution. By the end of this article, you’ll have a solid understanding of how to determine whether an array is monotonic and how to choose the most efficient approach.

What is Monotonic Arrays?

A monotonic array is an array that is entirely non-increasing or non-decreasing. In simpler terms, it means that the elements in the array are in either ascending or descending order. For instance, [1, 2, 3, 4, 5] and [5, 4, 3, 2, 1] are both monotonic arrays, while [1, 3, 2, 4, 5] is not.

Brute-Force Approach

Let’s start with the brute-force approach, which is relatively straightforward. We’ll iterate through the array and compare adjacent elements. If all adjacent elements maintain the same order (either all increasing or all decreasing), the array is considered monotonic.

def is_monotonic(arr):
    if len(arr) <= 2:
        return True
    increasing = decreasing = True
    for i in range(1, len(arr)):
        if arr[i] < arr[i - 1]:
            increasing = False
        if arr[i] > arr[i - 1]:
            decreasing = False

    return increasing or decreasing

In this code, we initialize two boolean variables, increasing and decreasing, to True. We then loop through the array, comparing adjacent elements. If any element breaks the monotonicity condition, we set the corresponding boolean variable to False. Finally, we return True if either increasing or decreasing is still True, indicating that the array is monotonic.

The brute-force approach works, but it’s not the most efficient solution, especially when dealing with large arrays. It has a time complexity of O(n), where n is the length of the array.

Optimized Single-Pass Approach [Better Approach]

A more efficient solution involves a single-pass approach that doesn’t require two separate loops for checking both increasing and decreasing monotonicity. Instead, we maintain a single variable to keep track of the direction and compare it with each element.

def is_monotonic_optimized(arr):
    if len(arr) <= 2:
        return True
    direction = 0  # 0 for unknown, 1 for increasing, -1 for decreasing
    for i in range(1, len(arr)):
        if arr[i] > arr[i - 1]:
            if direction == 0:
                direction = 1
            elif direction == -1:
                return False
        elif arr[i] < arr[i - 1]:
            if direction == 0:
                direction = -1
            elif direction == 1:
                return False

    return True

In this optimized approach, we use the direction variable to track the trend of the array. We initialize it as 0 to indicate an unknown direction. As we traverse the array, we compare each element with the previous one and determine the direction. If we encounter an element that doesn't conform to the current direction, we immediately return False. If we complete the loop without any issues, the array is monotonic, and we return `True.

This optimized approach is more efficient and has a time complexity of O(n), the same as the brute-force method, but it traverse through entire array only in worst cases.

Conclusion

In this blog post, we've explored two different approaches to check if an array is monotonic. The brute-force approach is relatively simple and straightforward but may not be the most efficient for large arrays. On the other hand, the optimized single-pass approach offers better performance and is a more elegant solution.

When choosing between the two methods, consider the size of your array and the desired efficiency. In most cases, the optimized single-pass approach is the preferred choice. It's concise, efficient, and offers a better performance guarantee.

Remember that understanding and being able to identify monotonic arrays are valuable skills in algorithm and data structure applications, as they can lead to more optimized solutions in various algorithms and problems.

Welcome to the Algo-World

Are you interested in learning about different types of algorithms and how they can be implemented in Python? Are you preparing for technical interviews with companies like Google, Facebook, Amazon, and other top tech companies? Then you’ve come to the right place! Welcome to our new blog on algorithms in Python.

You May Also Like…

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Welcome to Algo-world

You have Successfully Subscribed!