Find minimum length sub | C # implementation of the approach ; Function to return the minimum length of a sub - array which contains { 0 , 1 , 2 , 3 , 4 } as a sub - sequence ; To store the indices where 0 , 1 , 2 , 3 and 4 are present ; To store if there exist a valid prefix of sequence in array ; Base Case ; If current element is 0 ; Update the count of 0 s till now ; Push the index of the new 0 ; To check if previous element of the given sequence is found till now ; If it is the end of sequence ; Iterate for other elements of the sequence ; Binary Search to find closest occurrence less than equal to starting point ; Update the starting point ; Driver Code
using System ; class GFG { static int MAX_INT = 1000000 ; static int solve ( int [ ] array , int N ) { int [ , ] pos = new int [ 5 , 10000 ] ; int [ ] pref = new int [ 5 ] ; if ( array [ 0 ] == 0 ) { pref [ 0 ] = 1 ; pos [ 0 , pos . GetLength ( 0 ) - 1 ] = 0 ; } int ans = MAX_INT ; for ( int i = 1 ; i < N ; i ++ ) { if ( array [ i ] == 0 ) { pref [ 0 ] ++ ; pos [ 0 , pos . GetLength ( 0 ) - 1 ] = i ; } else { if ( pref [ array [ i ] - 1 ] > 0 ) { pref [ array [ i ] ] ++ ; pos [ array [ i ] , pos . GetLength ( 1 ) - 1 ] = i ; if ( array [ i ] == 4 ) { int end = i ; int start = i ; for ( int j = 3 ; j >= 0 ; j -- ) { int s = 0 ; int e = pos . GetLength ( 1 ) - 1 ; int temp = - 1 ; while ( s <= e ) { int m = ( s + e ) / 2 ; if ( pos [ j , m ] <= start ) { temp = pos [ j , m ] ; s = m + 1 ; } else e = m - 1 ; } start = temp ; } ans = Math . Min ( ans , end - start + 1 ) ; } } } } return ans ; } public static void Main ( String [ ] args ) { int [ ] array = { 0 , 1 , 2 , 3 , 4 , 2 , 0 , 3 , 4 } ; int N = array . Length ; Console . WriteLine ( solve ( array , N ) ) ; } }