Skip to content

Latest commit

 

History

History

2261

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p.

Two arrays nums1 and nums2 are said to be distinct if:

  • They are of different lengths, or
  • There exists at least one index i where nums1[i] != nums2[i].

A subarray is defined as a non-empty contiguous sequence of elements in an array.

 

Example 1:

Input: nums = [2,3,3,2,2], k = 2, p = 2
Output: 11
Explanation:
The elements at indices 0, 3, and 4 are divisible by p = 2.
The 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:
[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].
Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.
The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.

Example 2:

Input: nums = [1,2,3,4], k = 4, p = 1
Output: 10
Explanation:
All element of nums are divisible by p = 1.
Also, every subarray of nums will have at most 4 elements that are divisible by 1.
Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.

 

Constraints:

  • 1 <= nums.length <= 200
  • 1 <= nums[i], p <= 200
  • 1 <= k <= nums.length

 

Follow up:

Can you solve this problem in O(n2) time complexity?

Companies: Amazon, Uber

Related Topics:
Array, Hash Table, Trie, Rolling Hash, Hash Function, Enumeration

Similar Questions:

Hints:

  • Enumerate all subarrays and find the ones that satisfy all the conditions.
  • Use any suitable method to hash the subarrays to avoid duplicates.

Solution 1. Fixed Length Sliding Window + Rabin Karp

  • Use a fixed-length sliding window to count the number of elements divisible by p within the window
  • Use Rabin Karp to avoid duplicates subarrays
// OJ: https://leetcode.com/problems/k-divisible-elements-subarrays
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
public:
    int countDistinct(vector<int>& A, int k, int p) {
        int N = A.size(), ans = 0;
        for (int len = 1; len <= N; ++len) {
            unsigned long long cnt = 0, pow = 1, h = 0, d = 1099511628211;
            unordered_set<unsigned long long> seen;
            for (int i = 0; i < N; ++i) {
                if (i < len) pow *= d;
                h = h * d + A[i];
                cnt += A[i] % p == 0;
                if (i - len >= 0) {
                    cnt -= A[i - len] % p == 0;
                    h -= pow * A[i - len];
                }
                if (i >= len - 1 && cnt <= k && seen.count(h) == 0) {
                    ++ans;
                    seen.insert(h);
                }
            }
        }
        return ans;
    }
};