Skip to content
Related Articles

Related Articles

Smallest window containing 0, 1 and 2

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 02 Aug, 2022

Given a string S of size N consisting of the characters 0, 1 and 2, the 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:

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.

 

Approach: The idea of the approach is as mentioned below:

Use three pointers to store the indices of the elements 0, 1 and 2. When all the three elements are found, the distance between the maximum of them and the minimum of them is the minimum size window.
Keep updating the pointers whenever any of them is found again and calculate the size of the new window.

Follow the illustration below for a better understanding.

Illustration:

Consider S = “01212” and the three pointers to be zeroindex, oneindex and twoindex and set all of them to -1 initially.

When i = 0:
        => S[i] = ‘0’. zeroindex = 0, oneindex = -1, twoindex = -1
        => All of the values are not found. So no window is possible

When i = 1:
        => S[i] = ‘1’. zeroindex = 0, oneindex = 1, twoindex = -1
        => All of the values are not found. So no window is possible

When i = 2:
        => S[i] = ‘2’. zeroindex = 0, oneindex = 1, twoindex = 2
        => All of the values are found. 
        => Maximum is twoindex = 2. Minimum is zeroindex = 0.
        => So window size = (2 – 0 + 1) = 3.
        => Minimum window size = 3

When i = 3:
        => S[i] = ‘1’. zeroindex = 0, oneindex = 3, twoindex = 2
        => All of the values are found. 
        => Maximum is oneindex = 3. Minimum is zeroindex = 0.
        => So window size = (3 – 0 + 1) = 4.
        => Minimum window size = min (3, 4) = 3

When i = 4:
        => S[i] = ‘2’. zeroindex = 0, oneindex = 3, twoindex = 4
        => All of the values are found. 
        => Maximum is twoindex = 4. Minimum is zeroindex = 0.
        => So window size = (4 – 0 + 1) = 5.
        => Minimum window size = min(3, 5) = 3

So the size of the smallest window is 3

Follow the below steps to solve the problem:

  • Take three variable zero, one and two to check if 0, 1 and 2 are found in the window or not.
  • Take three variables zeroindex, oneindex and twoindex which will store indexes of 0, 1 and 2 when we encounter them.
  • Run the for loop for the whole length of String:
    • Update the indices of the values encountered.
    • Update the length of the window, if three of them are found.
    • Length will be the difference between the maximum and the minimum of the indexes of 0, 1 and 2.
  • And if all three values i.e., 0, 1, 2 are not found after the traversal is over then in that case return ‘-1’.

Below is the implementation of the above approach:

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the length of the smallest substring
int smallestSubstring(string S)
{
    int res = INT_MAX;
    // To check 0, 1 and 2
    bool zero = false, one = false, two = false;
    // To store indexes of 0, 1 and 2
    int zeroindex, oneindex, twoindex;
    for (int i = 0; i < S.length(); i++) {
        if (S[i] == '0') {
            zero = true;
            zeroindex = i;
        }
        else if (S[i] == '1') {
            one = true;
            oneindex = i;
        }
        else if (S[i] == '2') {
            two = true;
            twoindex = i;
        }
 
        // Calculating length
        if (zero and one and two)
            res = min(res,
                      max({ zeroindex, oneindex, twoindex })
                          - min({ zeroindex, oneindex, twoindex }));
    }
 
    // In case if there is no substring that contains 0,1 and 2
    if (res == INT_MAX)
        return -1;
    return res + 1;
}
 
// Driver Code
int main()
{
    string S = "01212";
 
    // Function call
    cout << smallestSubstring(S);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C program for above approach
 
#include <limits.h> // to use INT_MAX
#include <stdbool.h> //to use bool variable
#include <stdio.h>
 
// function to calculate max of two numbers
int min_two(int a, int b)
{
    if (a <= b)
        return a;
    else
        return b;
}
 
// function to calculate max of three numbers
int max_three(int a, int b, int c)
{
    if (a >= b && a >= c)
        return a;
    else if (b > a && b >= c)
        return b;
    else if (c > a && c > b)
        return c;
}
 
// function to calculate min of three numbers
int min_three(int a, int b, int c)
{
    if (a <= b && a <= c)
        return a;
    else if (b < a && b <= c)
        return b;
    else if (c < a && c < b)
        return c;
}
 
// Function to find the length of
// the smallest substring
int smallestSubstring(char S[], int n)
{
    int res = INT_MAX;
 
    // To check 0, 1 and 2
    bool zero = 0, one = 0, two = 0;
 
    // To store indexes of 0, 1 and 2
    int zeroindex, oneindex, twoindex;
    for (int i = 0; i < n; i++) {
        if (S[i] == '0') {
            zero = true;
            zeroindex = i;
        }
        else if (S[i] == '1') {
            one = true;
            oneindex = i;
        }
        else if (S[i] == '2') {
            two = true;
            twoindex = i;
        }
 
        // Calculating length
        if (zero && one && two)
            res = min_two( res,
                     max_three(zeroindex, oneindex, twoindex)
                    - min_three(zeroindex, oneindex, twoindex));
    }
 
    // In case if there is no substring that contains 0,1 and 2
    if (res == INT_MAX)
        return -1;
    return res + 1;
}
 
// Driver Code
int main()
{
    int n = 5; // size of string
    char S[] = "01212";
 
    int ans = smallestSubstring(S, n);
    // Function call
    printf("%d", ans);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java program for above approach
import java.util.*;
class GFG {
 
    // Function to find the length of the smallest substring
    public static int smallestSubstring(String S)
    {
        int res = Integer.MAX_VALUE;
 
        // To check 0, 1 and 2
        boolean zero = false, one = false, two = false;
 
        // To store indexes of 0, 1 and 2
        int zeroindex = 0, oneindex = 0, twoindex = 0;
        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == '0') {
                zero = true;
                zeroindex = i;
            }
            else if (S.charAt(i) == '1') {
                one = true;
                oneindex = i;
            }
            else if (S.charAt(i) == '2') {
                two = true;
                twoindex = i;
            }
 
            // Calculating length
            if (zero && one && two)
                res = Math.min( res,
                    Math.max(zeroindex,Math.max(oneindex, twoindex))
                  - Math.min( zeroindex,Math.min(oneindex, twoindex)));
        }
 
        // In case if there is no substring that contains 0,1 and 2
        if (res == Integer.MAX_VALUE)
            return -1;
        return res + 1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String S = "01212";
        // Function call
        System.out.print(smallestSubstring(S));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python code for the above approach
 
# Function to find the length of the smallest substring
 
 
def smallestSubstring(S):
    res = 999999
 
    # To check 0, 1 and 2
    zero = 0
    one = 0
    two = 0
 
    # To store indexes of 0, 1 and 2
    zeroindex = 0
    oneindex = 0
    twoindex = 0
    for i in range(len(S)):
        if (S[i] == '0'):
            zero = 1
            zeroindex = i
 
        elif (S[i] == '1'):
            one = 1
            oneindex = i
 
        elif (S[i] == '2'):
            two = 1
            twoindex = i
 
        # Calculating length
        if (zero and one and two):
            res = min(res,
                      max([zeroindex, oneindex, twoindex])
                      - min([zeroindex, oneindex, twoindex]))
 
    # In case if there is no substring that contains 0,1 and 2
    if (res == 999999):
        return -1
    return res + 1
 
 
# Driver Code
S = "01212"
 
# Function call
print(smallestSubstring(S))
 
# This code is contributed by Aditya Kumar (adityakumar129)


C#




// C# program for above approach
using System;
 
public class GFG {
 
    // Function to find the length of the smallest substring
    static int smallestSubstring(string S)
    {
        int res = Int32.MaxValue;
 
        // To check 0, 1 and 2
        bool zero = false, one = false, two = false;
 
        // To store indexes of 0, 1 and 2
        int zeroindex = 0, oneindex = 0, twoindex = 0;
        for (int i = 0; i < S.Length; i++) {
            if (S[i] == '0') {
                zero = true;
                zeroindex = i;
            }
            else if (S[i] == '1') {
                one = true;
                oneindex = i;
            }
            else if (S[i] == '2') {
                two = true;
                twoindex = i;
            }
 
            // Calculating length
            if (zero && one && two)
                res = Math.Min(res,
                    Math.Max( zeroindex, Math.Max(oneindex, twoindex))
                  - Math.Min( zeroindex, Math.Min(oneindex, twoindex)));
        }
 
        // In case if there is no substring that contains 0,1 and 2
        if (res == Int32.MaxValue)
            return -1;
        return res + 1;
    }
 
    // Driver Code
    static public void Main()
    {
        string S = "01212";
 
        // Function call
        Console.Write(smallestSubstring(S));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Javascript




<script>
    // JavaScript program for above approach
    const INT_MAX = 2147483647;
 
    // Function to find the length of
    // the smallest substring
    const smallestSubstring = (S) => {
        let res = INT_MAX;
 
        // To check 0, 1 and 2
        let zero = false, one = false, two = false;
 
        // To store indexes of 0, 1 and 2
        let zeroindex, oneindex, twoindex;
        for (let i = 0; i < S.length; i++) {
            if (S[i] == '0') {
                zero = true;
                zeroindex = i;
            }
            else if (S[i] == '1') {
                one = true;
                oneindex = i;
            }
            else if (S[i] == '2') {
                two = true;
                twoindex = i;
            }
 
            // Calculating length
            if (zero && one && two)
                res = Math.min(res,
                    Math.max(...[zeroindex, oneindex, twoindex])
                  - Math.min(...[zeroindex, oneindex, twoindex]));
        }
 
        // In case if there is no substring that contains 0,1 and 2
        if (res == INT_MAX)
            return -1;
        return res + 1;
    }
 
    // Driver Code
    let S = "01212";
 
    // Function call
    document.write(smallestSubstring(S));
 
    // This code is contributed by Aditya Kumar (adityakumar129)
 
</script>


Output

3

Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!