We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Continuous Subarrays

Difficulty: Medium


Problem Description

You are given a 0-indexed integer array nums. A subarray of nums is called continuous if for each pair of indices in the subarray, the absolute difference between the elements at those indices is less than or equal to 2. Return the total number of continuous subarrays.


Key Insights

  • A subarray can be defined by its starting and ending indices.
  • The condition for a continuous subarray is based on the maximum and minimum values within that subarray.
  • We can use a sliding window approach to efficiently find all valid subarrays.
  • The total number of valid subarrays can be derived from the length of the valid segment of the array.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can use a sliding window (two-pointer) technique. We maintain two pointers, start and end, which represent the current subarray. We expand the end pointer to include new elements and check if the current subarray meets the condition of continuity (i.e., the difference between the maximum and minimum values is at most 2). If it does, we count the number of new subarrays that can be formed with the current end index. If it doesn't, we move the start pointer to shrink the window until the condition is met again.


Code Solutions

def continuous_subarrays(nums):
    start = 0
    count = 0
    n = len(nums)
    
    for end in range(n):
        while max(nums[start:end+1]) - min(nums[start:end+1]) > 2:
            start += 1
        count += (end - start + 1)
    
    return count
← Back to All Questions