VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-window-containing-0-1-and-2/

⇱ Smallest window containing 0, 1 and 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest window containing 0, 1 and 2

Last Updated : 20 Apr, 2026

Given a string s consisting of the characters 0, 1 and 2, find the length of the smallest substring of string s that contains all the three characters 0, 1 and 2. If no such substring exists, then return -1.

Examples:

Input: s = "01212"
Output: 3
Explanation: The substring 012 is the smallest substring that contains the characters 0, 1 and 2.

Input: s = "12121"
Output: -1
Explanation:  As the character 0 is not present in the string s, therefore no substring containing all the three characters 0, 1 and 2 exists. Hence, the answer is -1 in this case.

Using Index Tracking - O(n) Time and O(1) Space

The idea is to keep track of the last seen indices of '0', '1', and '2' while iterating through the string. Once all three characters are found, compute the substring length as the difference between the maximum and minimum of the three indices. Update the minimum length found and print the result.


Output
3

Using a sliding window - O(n) Time and O(1) Space

The idea is to use two pointers (i and j) and a frequency array to track the count of '0', '1', and '2'. Expand the window by moving j, and when all three characters are present, shrink it from the left (i) to maintain the smallest valid substring. Print the minimum length found.

Dry run for string s = "01212":

  1. Initialize i = 0, j = 0, cnt = 0, min_len = INT_MAX and freq = {0, 0, 0}
  2. For j = 0, add '0': freq = {1, 0, 0}, cnt = 1 and cnt != 3 no update, expand window.
  3. For j = 1, add '1': freq = {1, 1, 0}, cnt = 2 and cnt != 3 no update, expand window.
  4. For j = 2, add '2': freq = {1, 1, 1}, cnt = 3. Now all digits are present hence, update min_len = min(INT_MAX, 2 - 0 + 1) = 3 and remove s[i] = '0': freq = {0, 1, 1}, increment i to 1, cnt = 2
  5. For j = 3, add '1': freq = {0, 2, 1}, cnt = 2 and cnt != 3 no update, expand window.
  6. For j = 4, add '2': freq = {0, 2, 2}, cnt = 2 and cnt != 3 no update, expand window.

So, final answer is min_len = 3.


Output
3
Comment