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:
- Initialize two flags:
increasinganddecreasing. Set them both tofalse. - Iterate through the array:
- For each element, check if it's greater than the previous one (if it exists). If so, set
increasingtotrueanddecreasingtofalse. Otherwise, if the current element is smaller than the previous one, setdecreasingtotrueandincreasingtofalse. - 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.
- For each element, check if it's greater than the previous one (if it exists). If so, set
- 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 istrue). - If both flags are
true, the array is alternating.
- If both are still
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
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";
}
}