HomeInterview QuestionsWhat would your logic look like for shrinking the …

What would your logic look like for shrinking the window from the left when finding the smallest window that contains all distinct error codes?

🟡 Medium Conceptual Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

To shrink the window from the left in a sliding‑window algorithm, you maintain a frequency map of the elements inside the current window and two pointers: left and right. As you expand the right pointer to include new error codes, you update the map. Once the window contains all distinct codes, you try to contract from the left: while the left element’s count is greater than one, decrement its count and move left forward. This keeps the window minimal for the current right position. After each contraction, you record the window size if it’s smaller than the best found so far. The algorithm runs in O(n) time because each element is visited at most twice (once by right, once by left). Pseudocode:

left = 0
freq = {}
unique_needed = number_of_distinct_codes
best = inf
for right in range(len(arr)):
    freq[arr[right]] += 1
    while len(freq) == unique_needed:
        best = min(best, right-left+1)
        freq[arr[left]] -= 1
        if freq[arr[left]] == 0:
            del freq[arr[left]]
        left += 1

This approach guarantees the smallest window that contains all distinct error codes.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500