709986. Smallest window containing 0, 1 and 2

Easy

Here is the detailed Markdown blog post for the problem:

Smallest window containing 0, 1 and 2

Summary

Given a binary string (only contains characters '0', '1' and '2'), find the smallest window that contains all three characters ('0', '1' and '2'). The solution should be in terms of minimum length.

Detailed Explanation

The problem can be solved using the sliding window algorithm, which is commonly used to solve problems involving arrays or strings. The basic idea is to maintain a window of elements that contain all the required characters, and slide the window until we find the smallest one.

Here's the step-by-step breakdown of the solution:

  1. Initialize two pointers start and end to 0.
  2. Initialize a variable min_length to infinity.
  3. Loop through the string:
    • If the current character is '0', increment start.
    • If the current character is '1' or '2', check if all three characters are present in the window [start, end]. If they are, update min_length with the length of the window.
  4. Continue the loop until we reach the end of the string.

Time complexity: O(n), where n is the length of the string. We only need to traverse the string once to find the smallest window.

Space complexity: O(1), as we are using a constant amount of space to store the pointers and the minimum length.

Here's an ASCII art diagram illustrating the sliding window:

 0 1 2 3 4 5
[  |  |  |  ]
start = 0, end = 0

In this example, the smallest window containing all three characters is [1, 3].

Optimized Solutions

Java

View on GeeksforGeeks
public int findSmallestWindow(String s) {
    int min_length = Integer.MAX_VALUE;
    for (int start = 0, end = 0; end < s.length(); end++) {
        if (s.charAt(end) == '0' || s.charAt(end) == '1') {
            start++;
        }
        if (start <= end && s.charAt(start) == '0' && s.charAt(end) == '2') {
            min_length = Math.min(min_length, end - start + 1);
        }
    }
    return min_length;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.