Lessons learned
Update:\n After years of LC and now clearly understanding Vortubac approach (this comment to be precise), I realize this is a Hard question which shouldn\'t be 
**Update**:\n* After years of LC and now clearly understanding Vortubac approach ([this comment to be precise](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/235235/C++Java-with-picture-prefixed-sliding-window/251836)), I realize this is a Hard question which shouldn\'t be either asked in an interview or couldn\'t be in solved in an intetview timeframe. Skipping this Q from my interview prep. But the Q teaches the concept of storing starting indices of other subarrays within the window (like prefix) during shrinking and expanding the sliding window. It is no more simply shrink and expand. This concept must be known.\n\n**Original**:\n* This seems like an advanced variation of https://leetcode.com/problems/subarrays-with-k-different-integers/ . The differnce is here finding the start of valid subarrays is tricky and requires an auxillary array.\n\n```\n// Incomplete\nclass Solution {\n    public int subarraysWithKDistinct(int[] nums, int k) {\n        int ans = 0;\n        Map<Integer, Integer> map = new HashMap<>();\n        int subarrayStart = 0;\n        int prefix = 0;\n        for (int windowStart = 0, windowEnd = 0; windowEnd < nums.length; ++windowEnd) {\n            map.put(nums[windowEnd], map.getOrDefault(nums[windowEnd], 0) + 1);\n            while (map.size() == k) {\n                ++prefix;\n                map.put(nums[windowStart], map.get(nums[windowStart]) - 1);\n                if (map.get(nums[windowStart]) == 0) {\n                    map.remove(nums[windowStart]);\n                }\n                ++windowStart;\n            }\n            ans += prefix;\n            \n            \n        }\n        \n        return ans;\n    }\n}\n```\n\n
[]