Count subarrays with at least k fruit pairs
UberSoftware Engineer · Online AssessmentLast updated
This question evaluates algorithmic problem-solving focused on frequency-based counting and efficient enumeration of subarrays, testing competence in designing subquadratic solutions and selecting appropriate data representations within the Coding & Algorithms domain.
Given an integer array nums where each value denotes a fruit type, and an integer k: For any subarray, define a 'pair' for fruit value v if its frequency in the subarray is at least 2; each fruit contributes at most one pair regardless of appearing more than twice. Return the number of subarrays whose number of such pairs is at least k. Example: nums = [0, 1, 0, 1, 0], k = 2 → 3 (valid subarrays are [0, 1, 0, 1], [1, 0, 1, 0], and [0, 1, 0, 1, 0]). Design an algorithm better than O(n^ 2), explain your approach (e.g., sliding window or two pointers), and analyze complexity.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.