Taro Logo

Count Strictly Increasing Subarrays

Medium
Asked by:
Bridgewater Associates
1 view
Topics:
Arrays

You are given an array nums consisting of positive integers.

Return the number of subarrays of nums that are in strictly increasing order.

A subarray is a contiguous part of an array.

Example 1:

Input: nums = [1,3,5,4,4,6]
Output: 10
Explanation: The strictly increasing subarrays are the following:
- Subarrays of length 1: [1], [3], [5], [4], [4], [6].
- Subarrays of length 2: [1,3], [3,5], [4,6].
- Subarrays of length 3: [1,3,5].
The total number of subarrays is 6 + 3 + 1 = 10.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 15
Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty or contains only a single element?
  2. How should consecutive duplicate values (e.g., [1, 2, 2, 3]) be handled regarding strictly increasing subarrays?
  3. Can the input array contain negative numbers and zeros, or are we guaranteed only positive integers?
  4. What is the maximum expected length of the input array to avoid potential integer overflow with the return value?
  5. Could you clarify the definition of a subarray in this context—does a single element count as a strictly increasing subarray of length 1?

Brute Force Solution

Approach

Imagine you have a sequence of numbers and want to find every possible chunk where each number is strictly larger than the one before it. The brute force strategy involves testing every single possible group of consecutive numbers to see if it follows this increasing rule.

Here's how the algorithm would work step-by-step:

  1. Start by looking at every possible starting point in the sequence of numbers.
  2. For each starting point, consider every possible ending point that comes after it, creating chunks of numbers of varying lengths.
  3. Examine each chunk from start to finish to check if every number is strictly greater than the number immediately preceding it.
  4. If the chunk successfully meets this increasing condition, count it as a valid discovery.
  5. Repeat this checking process for every single possible chunk you can form.
  6. Keep a running total of all the chunks that successfully followed the increasing rule from start to finish.
  7. Return the final total count after you have checked every possible combination of chunks.

Code Implementation

def count_strictly_increasing_subarrays(sequence):    total_increasing_count = 0        # We test every possible starting point to examine all potential subarray combinations    for starting_index in range(len(sequence)):        for ending_index in range(starting_index, len(sequence)):            is_strictly_increasing = True                        for current_index in range(starting_index + 1, ending_index + 1):                if sequence[current_index] <= sequence[current_index - 1]:                    is_strictly_increasing = False                    break                        # We only count chunks that successfully maintained the strictly increasing condition            if is_strictly_increasing:                total_increasing_count += 1                    return total_increasing_count

Big(O) Analysis

Time Complexity
O(n²) – The time complexity is driven by the nested iteration required to evaluate every possible chunk of the array of size n. For each of the n possible starting points, we examine every potential ending point, creating various chunks. Within these nested loops, validating if a chunk is strictly increasing takes work proportional to the length of that chunk. Summing the checks for all possible chunks results in approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute force strategy described only utilizes a few primitive integer variables to maintain running totals, indices, and loop counters. These variables take up a constant amount of extra memory regardless of the input size N. Since no auxiliary data structures, temporary lists, or recursion stack frames are created, the auxiliary space remains entirely independent of N. Therefore, the space complexity simplifies to Big O of 1.

Optimal Solution

Approach

Instead of checking every single possible sequence one by one, the optimal approach scans through the collection from left to right while keeping a running tally of how many consecutive items are growing larger. By simply adding up the lengths of these growing streaks as you discover them, you can instantly figure out the total number of valid increasing sections without doing repetitive work.

Here's how the algorithm would work step-by-step:

  1. Begin scanning the items from left to right, treating the very first item as the start of your current growing streak.
  2. As you look at each next item, check if it is strictly greater than the item immediately before it.
  3. If the new item continues the upward trend, increase your current streak count by one to show that the streak has grown longer.
  4. If the new item breaks the trend or stays the same, reset your current streak count back to the baseline because the old streak has ended.
  5. Every single time you confirm a growing step, immediately add the current streak count to your running total of valid sections.
  6. Continue this process until you reach the very end of the collection, allowing you to tally all possible increasing sections in one single pass.

Code Implementation

def count_strictly_increasing_subarrays(sequence):    if not sequence:        return 0    total_increasing_count = 0    current_streak_count = 1    # We iterate through the array starting from the second element to compare with predecessors.    for index in range(1, len(sequence)):        if sequence[index] > sequence[index - 1]:            current_streak_count += 1        else:            # A broken trend forces a streak reset because non-increasing elements terminate continuity.            current_streak_count = 1        total_increasing_count += current_streak_count    # Returning the accumulated sum gives the exact total of all valid increasing sections.    return total_increasing_count

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the array of size n, where we scan elements from left to right. At each step, we perform a constant amount of work by comparing the current item to the previous one and updating our running streak and total count. Since we only visit each element once without using nested loops or recursive calls, the total number of operations grows linearly with the input size. This directly translates to a linear time complexity of O(n).
Space Complexity
O(1) – To calculate the total number of strictly increasing subarrays, the algorithm only allocates a fixed number of scalar variables to maintain the running tally, the current streak count, and the loop index. These primitive variables require a constant amount of memory that does not scale with the input size N. Since no additional data structures, auxiliary arrays, or recursive stack frames are utilized during the single-pass scan, the auxiliary space remains entirely independent of N. Therefore, the extra memory used by the algorithm simplifies to a constant time-equivalent space complexity of O(1).

Edge Cases

Empty or null input array
How to Handle:
Return zero immediately as an empty array contains no subarrays.
Array with a single element
How to Handle:
Return zero or one based on problem definition, but typically return one since a single element is a strictly increasing subarray of length one.
Array with all identical elements
How to Handle:
The algorithm resets the streak count on equality, correctly resulting in a total count equal to the array length.
Array in strictly decreasing order
How to Handle:
The streak never extends beyond length one, yielding a total count equal to the array length.
Array containing negative numbers and zeros
How to Handle:
The strict greater-than comparison handles negative numbers and zeros seamlessly without any special offset.
Extremely large array with maximum possible constraints
How to Handle:
A single-pass linear scan with O(1) extra space ensures optimal performance without exceeding time or memory limits.
Very long strictly increasing sequence causing integer overflow
How to Handle:
Using a 64-bit integer type for the total count accumulator prevents arithmetic overflow when summing large arithmetic progressions.
Alternating values like 1, 2, 1, 2
How to Handle:
The running streak counter correctly resets whenever the sequence breaks and restarts on the next element.