![]() |
VOOZH | about |
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.
Table of Content
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.
3
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":
So, final answer is min_len = 3.
3