Taro Logo

Count Good Subarrays

Hard
Asked by:
Harness
BNY
6 views
Topics:
ArraysBit Manipulation

You are given an integer array nums.

A subarray is called good if the bitwise OR of all its elements is equal to at least one element present in that subarray.

Return the number of good subarrays in nums.

Here, the bitwise OR of two integers a and b is denoted by a | b.

Example 1:

Input: nums = [4,2,3]

Output: 4

Explanation:

The subarrays of nums are:

Subarray Bitwise OR Present in Subarray
[4] 4 = 4 Yes
[2] 2 = 2 Yes
[3] 3 = 3 Yes
[4, 2] 4 | 2 = 6 No
[2, 3] 2 | 3 = 3 Yes
[4, 2, 3] 4 | 2 | 3 = 7 No

Thus, the good subarrays of nums are [4], [2], [3] and [2, 3]. Thus, the answer is 4.

Example 2:

Input: nums = [1,3,1]

Output: 6

Explanation:

Any subarray of nums containing 3 has bitwise OR equal to 3, and subarrays containing only 1 have bitwise OR equal to 1.

In both cases, the result is present in the subarray, so all subarrays are good, and the answer is 6.

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109

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 is the definition of a "pair of identical elements"? Does a group of $x$ identical elements contribute $\frac{x(x-1)}{2}$ pairs, or are we strictly counting non-overlapping pairs?
  2. Can the array contain negative numbers, or are the elements guaranteed to be non-negative integers?
  3. What should be returned if no good subarrays exist in the input array?
  4. How are subarrays defined regarding their boundaries? Are single-element subarrays or empty subarrays possible inputs, and how do they factor into $k$?
  5. Could $k$ be zero or negative, and if so, does every possible subarray automatically qualify as a good subarray?

Brute Force Solution

Approach

The brute force approach to finding good groups of items involves checking every single possible sub-group you can possibly make from the original collection. For each sub-group you create, you test it to see if it meets the definition of being good, and you keep a running tally of how many success stories you find.

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

  1. Look at the entire collection of items laid out in front of you.
  2. Start by picking a single item to form a very small group and check if that tiny group is good.
  3. Expand your group by adding the very next item right beside it and check if this new, slightly larger group is good.
  4. Keep adding items one by one to the end of your current group, testing each new grouping to see if it qualifies as good.
  5. Once you have checked every possible group that starts with your very first item, move your starting point to the second item.
  6. Repeat the exact same process of growing the group item by item and checking each combination.
  7. Continue this pattern of moving your starting point and trying every possible ending point until you have examined every single continuous slice of the collection.
  8. Count up all the groups that passed the test as you went along to get your final answer.

Code Implementation

def count_good_subarrays(collection):    good_subarrays_tally = 0    # Iterate through every possible starting point to examine all continuous slices    for start_index in range(len(collection)):        for end_index in range(start_index, len(collection)):            current_subarray = collection[start_index:end_index + 1]            # A subarray is considered good if it contains at least one duplicate pair of items            if len(current_subarray) != len(set(current_subarray)):                good_subarrays_tally += 1    return good_subarrays_tally

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses nested iterations where the outer loop sets the starting point of the subarray and moves across all n items. The inner loop expands the group one element at a time to check every possible ending point for that start. Summing the work for each starting position results in roughly n * (n + 1) / 2 total operations, which simplifies to O(n²).
Space Complexity
O(1) – To keep track of the running tally and the boundaries of each continuous slice of the collection as you expand your group item by item, the algorithm only needs a few primitive integer variables. These variables require a constant amount of extra memory regardless of how large the input collection grows. Because no additional data structures like hash maps or temporary lists scale with the input size N, the auxiliary space remains entirely flat. Ultimately, the extra memory used simplifies to Big O of 1.

Optimal Solution

Approach

Instead of checking every single possible group one by one, we can look at chunks of items and expand them wisely. Whenever we find a valid group, we realize that extending it further will also keep it valid, allowing us to count many successful groups all at once.

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

  1. Imagine moving a sliding window across our line of items, starting with the very first item.
  2. Keep expanding the right side of our window to include more items until the current group meets our special condition.
  3. The moment the group meets the condition, pause and realize that adding any future items to the right side of this exact group will also satisfy the condition.
  4. Count all these newly enabled possibilities in one go, because they all share the same starting point.
  5. Once you have counted them, gently shrink the window from the left side to see how compact we can make the group while still keeping it valid.
  6. Repeat this process of expanding the right side and shrinking the left side until you reach the end of the line.
  7. By adding up all the valid groups found at each expansion, you quickly arrive at the total answer without wasting time checking hopeless combinations.

Code Implementation

def count_good_subarrays(items_array, target_condition):    window_left = 0
    total_good_groups = 0
    frequency_map = {}
    current_pairs = 0

    for window_right in range(len(items_array)):
        current_item = items_array[window_right]
        current_pairs += frequency_map.get(current_item, 0)
        frequency_map[current_item] = frequency_map.get(current_item, 0) + 1

        # Once condition is met, all extensions to the right are also valid subarrays.
        while current_pairs >= target_condition:
            total_good_groups += len(items_array) - window_right
            left_item = items_array[window_left]
            frequency_map[left_item] -= 1
            current_pairs -= frequency_map[left_item]
            window_left += 1

    return total_good_groups

Big(O) Analysis

Time Complexity
O(n) – As the sliding window moves across the n items, the right pointer expands the window by iterating through the array at most once. Simultaneously, whenever a valid condition is met, the left pointer shrinks the window, and since it only moves forward and never resets, it traverses the array at most once as well. Because both pointers visit each element a constant number of times, the total operations scale linearly with n. This amounts to approximately 2n total pointer movements, which simplifies to O(n).
Space Complexity
O(1) – The algorithm uses a sliding window approach with a few primitive integer variables to track the left and right boundaries and the element counts. Because these variables consume a constant amount of memory regardless of the input size N, no additional auxiliary data structures scale with N. Therefore, the extra auxiliary space complexity is strictly constant.

Edge Cases

Array length is less than 2
How to Handle:
Return zero immediately since it is impossible to form a pair of identical elements.
Array size is extremely large up to one hundred thousand elements
How to Handle:
Use an O(n) sliding window approach with a hash map to ensure optimal scaling and avoid time limit exceeded errors.
All elements in the array are identical
How to Handle:
The sliding window correctly calculates combinations using binomial coefficients to count all valid subarrays efficiently.
No subarray contains at least k pairs
How to Handle:
The algorithm will process the entire array and naturally return a total count of zero.
The value of k is zero or negative
How to Handle:
All possible subarrays are considered good by definition, so the function should return the total number of possible subarrays n times n plus one divided by two.
Target k is larger than the total possible pairs in the entire array
How to Handle:
The sliding window expands to the end and returns zero because the condition is never satisfied.
Integer overflow from counting too many good subarrays
How to Handle:
Use sixty-four-bit integers for the answer accumulator since the maximum number of subarrays can exceed standard thirty-two-bit integer limits.
Array contains negative numbers and zeros
How to Handle:
The hash map treats negative numbers and zeros the same as positive numbers since equality checks function identically for all integers.