Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Smallest window of 0, 1 and 2

Easy Acceptance 50% Points 20

Given a string S consisting of the characters 0, 1 and 2. Your task is to 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
Example 1

Example 1

Input: S = 10212

Output: 3

Explanation: The substring 102 is the smallest substring that contains the characters 0, 1 and 2.

Example 2

Example 2

Input: S = 12121

Output: -1

Explanation: As the character 0 is not present in the string S, therefor no substring containing all the three characters 0, 1 and 2 exists. Hence, the answer is -1 in this case.

Constraints
  • 1 = length( S ) = 10^5
  • All the characters of String S lies in the set {'0', '1', '2'}
Topics
String
Companies
Paytm
Added 19 Jul 2026 50% acceptance
Ln 1, Col 1Sign in to save your code
10212
3