Adjacent Increasing Subarrays Detection I Solution in Java


Problem Description

So, you think you can just stroll through an array of numbers and find increasing subarrays like it’s a walk in the park? Well, think again! The problem at hand is to determine if there exists a subarray of length at least k where the elements are strictly increasing. Imagine you’re at a party, and you want to find a group of friends who are all taller than you. If you can’t find at least k of them standing in a row, you might as well go home!

In simpler terms, given an array of integers, you need to check if there’s a sequence of at least k numbers that are in increasing order. If you can find such a sequence, you’re golden! If not, well, better luck next time.

Code Solution

Here’s the Java solution that does all the heavy lifting for you:


class Solution {
  public boolean hasIncreasingSubarrays(List nums, int k) {
    int increasing = 1;
    int prevIncreasing = 0;

    for (int i = 1; i < nums.size(); ++i) {
      if (nums.get(i) > nums.get(i - 1)) {
        ++increasing;
      } else {
        prevIncreasing = increasing;
        increasing = 1;
      }
      if (increasing / 2 >= k || Math.min(prevIncreasing, increasing) >= k)
        return true;
    }

    return false;
  }
}

Approach

The approach here is as straightforward as it gets. We traverse through the list of numbers, keeping track of how many consecutive numbers are increasing. If we find a number that’s not greater than the previous one, we reset our count. The magic happens when we check if our count of increasing numbers is at least k. If it is, we return true. If we finish the loop without finding such a sequence, we return false. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n), where n is the number of elements in the list. We only traverse the list once.
Space Complexity O(1), as we are using a constant amount of space for our variables.

Real-World Example

Imagine you’re at a concert, and you want to find a group of friends who are all taller than you to get a better view. If you can find at least k friends standing in a row who are taller than you, you can finally enjoy the concert without straining your neck. This problem is just like that! You’re looking for a sequence of numbers (or friends) that are increasing in height (or value).

Similar Problems

If you enjoyed this problem, you might want to check out these similar challenges:

  • 3-Sum Solution in Java