← Meta Interview Insights

Meta·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
May 2026

Summary

Meta SWE coding round with a sliding window problem. Pretty standard stuff but the edge cases tripped me up more than I'd like to admit.

Questions Asked (1)

Q1

Given a string and an integer n, find the length of the shortest substring that contains exactly n distinct characters. Return -1 if no such substring exists.

Algorithms & Data Structures
Author's notes

Sliding window was the right move and I knew it pretty quickly.

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 n distinct characters, expanding the right pointer and shrinking the left pointer when the distinct count exceeds n. Track the minimum length whenever the window contains exactly n distinct characters. If no such window is found, return -1.

Pro tip: Clarify edge cases upfront (e.g., n <= 0, n > distinct characters in string) and mention that the sliding window approach runs in O(N) time and O(1) space for a fixed alphabet, which is optimal for this problem.

1. Clarify requirements and edge cases

Confirm the definition of 'substring' (contiguous), handle cases like n <= 0, n greater than the number of distinct characters in the string, and empty string. Discuss return value -1 when no such substring exists.

2. Choose the sliding window approach

Explain that a brute-force check of all substrings would be O(N^2) or worse, so a two-pointer sliding window is optimal. Maintain a frequency map of characters in the current window and a count of distinct characters.

3. Expand and contract the window

Move the right pointer to include new characters. When the distinct count exceeds n, move the left pointer to shrink the window until the distinct count is at most n. Whenever the distinct count equals n, update the minimum length.

4. Track and return the result

Keep a variable for the minimum length found, initialized to infinity. After processing, return the minimum length if it was updated, otherwise return -1.

5. Analyze complexity and test

State that the time complexity is O(N) because each character is visited at most twice, and space is O(1) for a fixed alphabet (or O(k) where k is the number of distinct characters). Walk through a small example to verify correctness.

Key Points to Mention

  • Sliding window technique with two pointers (left and right).
  • Use a hash map or array to count character frequencies and track distinct characters.
  • Update the minimum length only when the window has exactly n distinct characters.
  • Handle edge cases: n <= 0, n > total distinct characters, empty string.
  • Time complexity O(N) and space complexity O(1) for fixed alphabet (or O(k)).
  • Return -1 if no valid substring is found.

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