Minimum subsequences of a string A required to be appended to obtain the string B | Python3 program for the above approach ; Function to count the minimum subsequences of a A required to be appended to obtain the B ; Size of the string ; Maps characters to their respective indices ; Insert indices of characters into the sets ; Stores the position of the last visited index in the A . Initially set it to - 1. ; Stores the required count ; Iterate over the characters of B ; If the character in B is not present in A , return - 1 ; Fetch the next index from B [ i ] 's set ; If the iterator points to the end of that set ; If it doesn 't poto the  end, update previous ; Prthe answer ; Driver Code
from bisect import bisect_right NEW_LINE def countminOpsToConstructAString ( A , B ) : NEW_LINE INDENT N = len ( A ) NEW_LINE i = 0 NEW_LINE mp = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ ord ( A [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT previous = - 1 NEW_LINE ans , i = 1 , 0 NEW_LINE while i < len ( B ) : NEW_LINE INDENT ch = B [ i ] NEW_LINE if ( len ( mp [ ord ( ch ) - ord ( ' a ' ) ] ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT it = bisect_right ( mp [ ord ( ch ) - ord ( ' a ' ) ] , previous ) NEW_LINE if ( it == len ( mp [ ord ( ch ) - ord ( ' a ' ) ] ) ) : NEW_LINE INDENT previous = - 1 NEW_LINE ans += 1 NEW_LINE continue NEW_LINE DEDENT previous = mp [ ord ( ch ) - ord ( ' a ' ) ] [ it ] NEW_LINE i += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B = " abc " , " abac " NEW_LINE countminOpsToConstructAString ( A , B ) NEW_LINE DEDENT