702896. Type of array

Basic

Type of Array

Slug: type-of-array4605

Difficulty: Basic

Id: 702896

Topic Tags: Arrays, Data Structures

Company Tags: Amazon

Summary

Given an array of integers, determine its type. The types are:

  • Monotonic: The array is either strictly increasing or decreasing.
  • Alternating: The array alternates between increasing and decreasing subsequences.

We will focus on developing a solution that can classify the given array into one of these two types.

Detailed Explanation

To solve this problem, we'll use a simple algorithmic approach. We'll iterate through the array, keeping track of whether it's currently increasing or decreasing. If we encounter an element that doesn't follow the current trend (i.e., it's not increasing if we were previously increasing, and vice versa), we know that the array is alternating.

Here's a step-by-step breakdown:

  1. Initialize two flags: increasing and decreasing. Set them both to false.
  2. Iterate through the array:
    • For each element, check if it's greater than the previous one (if it exists). If so, set increasing to true and decreasing to false. Otherwise, if the current element is smaller than the previous one, set decreasing to true and increasing to false.
    • If we encounter an element that doesn't follow the current trend (i.e., it's not increasing if we were previously increasing, and vice versa), we know that the array is alternating.
  3. After the loop, check the flags:
    • If both are still false, the array is neither monotonic nor alternating.
    • If only one flag is true, the array is either strictly increasing or decreasing (depending on which flag is true).
    • If both flags are true, the array is alternating.

Time complexity: O(n), where n is the length of the array. We're making a single pass through the array. Space complexity: O(1), as we're using a constant amount of space to store the two flags.

Optimized Solutions

Java

View on GeeksforGeeks
public String typeOfArray(int[] arr) {
    boolean increasing = false;
    boolean decreasing = false;

    for (int i = 1; i < arr.length; i++) {
        if (arr[i] > arr[i - 1]) {
            if (!increasing && !decreasing) {
                increasing = true;
            } else if (!increasing && decreasing) {
                return "Alternating";
            }
        } else if (arr[i] < arr[i - 1]) {
            if (!decreasing && !increasing) {
                decreasing = true;
            } else if (!decreasing && increasing) {
                return "Alternating";
            }
        }
    }

    if (increasing) {
        return "Monotonic Increasing";
    } else if (decreasing) {
        return "Monotonic Decreasing";
    } else {
        return "Not Monotonic or Alternating";
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.