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
posto store the last positions of 0, 1, and 2 in the string. InitializeouttoINT_MAX.Iterate through the string, updating the positions of 0, 1, and 2 in the
posvector.For each character, calculate the minimum and maximum positions in the
posvector.If the minimum position is not
-1, updateoutwith the minimum window size.Return the minimum window size if found, otherwise return -1.
Time and Auxiliary Space Complexity
Time Complexity:
O(N), whereNis the length of the input string. The algorithm iterates through the string once.Auxiliary Space Complexity:
O(1), as the size of theposvector 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
Was this helpful?