03. Smallest window containing 0, 1 and 2
The problem can be found at the following link: Question Link
My Approach
To find the smallest window containing 0, 1, and 2, I used a sliding window approach. Here are the steps:
Initialize a vector
pos
to store the last positions of 0, 1, and 2 in the string. Initializeout
toINT_MAX
.Iterate through the string, updating the positions of 0, 1, and 2 in the
pos
vector.For each character, calculate the minimum and maximum positions in the
pos
vector.If the minimum position is not
-1
, updateout
with the minimum window size.Return the minimum window size if found, otherwise return -1.
Time and Auxiliary Space Complexity
Time Complexity:
O(N)
, whereN
is the length of the input string. The algorithm iterates through the string once.Auxiliary Space Complexity:
O(1)
, as the size of thepos
vector is constant.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated