#2261

K Divisible Elements Subarrays

Medium
ArrayHash TableTrieRolling HashHash FunctionEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(n)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution uses a sliding window approach to efficiently count the number of divisible elements while generating subarrays. This reduces the need for nested loops and allows us to keep track of distinct subarrays using a hash set.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a set to store distinct subarrays.
  2. 2Step 2: Use a sliding window approach to traverse the array.
  3. 3Step 3: Maintain a count of elements divisible by p within the window.
  4. 4Step 4: For each valid window, generate subarrays and add them to the set.
  5. 5Step 5: Return the size of the set as the result.
solution.py12 lines
1def countDistinct(nums, k, p):
2    distinct_subarrays = set()
3    n = len(nums)
4    for start in range(n):
5        count = 0
6        for end in range(start, n):
7            if nums[end] % p == 0:
8                count += 1
9            if count > k:
10                break
11            distinct_subarrays.add(tuple(nums[start:end + 1]))
12    return len(distinct_subarrays)

Complexity note: The time complexity remains O(n²) due to the nested loops, but we avoid unnecessary checks by breaking early when the count exceeds k. The space complexity is O(n) for storing distinct subarrays.

  • 1Using a set to store subarrays helps in avoiding duplicates.
  • 2Early termination of loops can significantly reduce unnecessary computations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.