← Google Interview Insights

Google·Software Engineer·Onsite - Coding / Algorithms·Intermediate

IntermediatePrefer not to say
Apr 2026

Summary

Google SWE coding round, one algorithmic problem on shortest subarray with k distinct integers. Pretty standard sliding window territory but the implementation details trip you up if you're not careful.

Questions Asked (1)

Q1

Given an integer array and an integer k, find the length of the shortest contiguous subarray that contains at least k distinct integers. Return -1 if no such subarray exists.

Algorithms & Data Structures
Author's notes

I jumped straight to brute force and talked through the O(n^2) approach first, which was fine, but I fumbled a bit explaining why contracting the left pointer was safe while keeping the distinct count valid.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a sliding window (two pointers) to maintain a window with at most k distinct integers, expanding the right pointer and shrinking the left pointer when the distinct count reaches k. Track the minimum window length that contains exactly k distinct integers, and return -1 if no such window exists.

Pro tip: Clarify edge cases upfront (e.g., k > distinct elements in array, empty array) and discuss time/space complexity (O(n) time, O(k) space) to demonstrate thoroughness.

1. Understand the problem and edge cases

Restate the problem to ensure clarity. Identify edge cases: k <= 0, k > number of distinct elements, empty array, and array with all identical elements.

2. Choose the sliding window approach

Explain that a sliding window with two pointers efficiently finds the shortest subarray by maintaining a window with at most k distinct integers.

3. Implement the algorithm

Initialize left=0, a frequency map, and min_length=infinity. Expand right, update frequency, and while distinct count == k, update min_length and shrink from left.

4. Handle the result and complexity

After traversal, return min_length if found, else -1. State time complexity O(n) and space complexity O(k) due to the frequency map.

Key Points to Mention

  • Sliding window technique with two pointers
  • Hash map to track frequency of elements in the current window
  • Condition to shrink window when distinct count equals k
  • Tracking minimum length and updating it during shrinking
  • Edge cases: k > distinct elements, empty array, k <= 0
  • Time and space complexity analysis

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.