O(N) C++ solution using Suffix array template.
I used O(N log N) template of suffix array but you can use O(N) template.\nRest I used LCP array for removing duplicate subarray , and suffix array to get total
I used O(N log N) template of suffix array but you can use O(N) template.\nRest I used LCP array for removing duplicate subarray , and suffix array to get total subarrays.\nyou can get suffix array and lcp array template here https://cp-algorithms.com/string/suffix-array.html.\nmy template of suffix array function and lcp array, you can get here https://p.ip.fi/b1qd\n```\nvector<int> boundary(vector<int> &v,int k,int p){\n\t/// Function for getting right boundary for each index for at most k divisible elements by p\n    int n = v.size();\n\tvector<int> ret(n);\n\tfor(int i = n-1, j = n - 1; i >= 0; i--){\n\t\tk -= v[i] % p == 0;\n\t\twhile(k < 0) {k += v[j--] % p == 0;}\n\t\tret[i] = j + 1;\n\t}\n\treturn ret;\n}\nclass Solution {\npublic:\n    int countDistinct(vector<int>& nums, int k, int p) {\n        vector<int> vv = boundary(nums,k,p) , lcp = lcp_array(nums) , sfx = suffix_array(nums);\n        int ans = 0 , n = nums.size();\n        for(int i = 0; i < n; i++)    \n            ans += vv[sfx[i]] - sfx[i];\n        for(int i = 0; i + 1 < n; i++) \n            ans -= min(vv[sfx[i]] - sfx[i], lcp[i]);\n        return ans;\n    }\n};\n```
['Sliding Window']