← IBM Interview Insights

IBM·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
Jun 2026

Summary

Did a coding round at IBM for a software engineer role. Pretty standard algorithmic stuff, one question on sliding windows that I thought I had but second-guessed myself halfway through.

Questions Asked (1)

Q1

Given an integer array and an integer k, find the minimum length of a contiguous subarray that contains exactly k distinct numbers. Return -1 if no valid subarray exists.

Algorithms & Data Structures
Author's notes

I knew sliding window was the right move but fumbled the part where you shrink from the left while keeping the distinct count at exactly k.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use a sliding window (two-pointer) technique to maintain a window with at most k distinct numbers, expanding the right pointer and shrinking the left pointer when the distinct count exceeds k. Track the minimum window length whenever the distinct count equals k. If no such window is found, return -1.

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

1. Clarify and Validate Input

Confirm constraints: array size, possible values, and k. Handle edge cases like k=0 or k > total distinct elements by returning -1 immediately.

2. Initialize Sliding Window

Use two pointers (left, right) and a hash map to count frequencies of elements in the current window. Initialize min_length to infinity.

3. Expand and Contract Window

Move right pointer to include new elements. While distinct count > k, move left pointer to shrink window. When distinct count == k, update min_length.

4. Return Result

After traversal, if min_length is still infinity, return -1; otherwise return min_length.

Key Points to Mention

  • Sliding window technique with two pointers
  • Hash map to track frequencies and distinct count
  • Time complexity O(n) and space complexity O(k)
  • Handling edge cases: k=0, k > distinct elements, empty array
  • Updating minimum length only when distinct count equals k
  • Shrinking window when distinct count exceeds k

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