Clean Java
It varies between framework version; in older versions StringBuilder works on a string directly, so there is no additional cost in .ToString(): it just hands yo
It varies between framework version; in older versions StringBuilder works on a string directly, so there is no additional cost in .ToString(): it just hands you the data directly (which can mean oversized, but it makes it work); so O(1).\n\nIn newer framework version, it uses a char[] backing buffer, so now when you .ToString() it will probably need to copy 2 x Length bytes, making it O(N).\n```\nclass Solution {\n    public int countDistinct(int[] nums, int k, int p) {\n        Set<String> set = new HashSet<>();\n        getAll(nums, set, k, p);\n        return set.size();\n    }\n    \n    private void getAll(int[] nums, Set<String> res, int k, int p) {\n        int N = nums.length;\n        for (int i = 0; i < N; i++) {\n            StringBuilder sb = new StringBuilder();\n            int countK = 0;\n            for (int j = i; j < N && countK <= k; j++) {\n                if (nums[j] % p == 0) countK++;\n                sb.append(",").append(nums[j]);\n                if (countK <= k) res.add(sb.toString());\n            }\n        }\n    }\n}\n```
['Java']