Bob has a string 'S' of length 'N' which he enjoys playing with. After each day, he appends the initial string 'S' to the one that he currently has. For example, if 'S' = "xyz", on the first day, the string will become "xyz", on the second day, the string becomes "xyzxyz", on the third day, the string becomes "xyzxyzxyz", and so on.
Alice has another string 'T' of length 'M'. She is curious about the earliest day when her string 'T' can be found as a subsequence in Bob's growing string.
Can you help Alice figure out the earliest day?
Let 'N' = 3, 'S' = "xyz", M = 3, T = "xyz".
Bob's string on Day 1 is "xyz".
Is "xyz" a subsequence of "xyz"? Yes.
The earliest day is 1.
Thus, the answer is 1.
The first line contains two integers, 'N' and 'M'.
The second line contains the string 'S' of length 'N'.
The third line contains the string 'T' of length 'M'.
Output Format :
Return the earliest day (a positive integer starting from 1) when 'T' appears as a subsequence in Bob's string. If 'T' can never be formed as a subsequence, return -1.
Note :
You don’t need to print anything. Just implement the given function.
1 <= 'N', 'M' <= 10^5
'a' <= 'S', 'T' <= 'z'
Time Limit: 1 sec
2 2
ab
ba
2
Let N = 2, S = "ab", M = 2, T = "ba".
Bob's string on Day 1 is "ab".
Is "ba" a subsequence of "ab"? No.
Bob's string on Day 2 is "abab".
Is "ba" a subsequence of "abab"? Yes, for example, using the 'b' at index 1 and the 'a' at index 2 (0-based indexing in the combined string).
The earliest day is 2.
Thus, the answer is 2.
3 3
abc
acb
2
Consider dynamic programming where the state keeps track of the prefix of 'T' matched so far and the position in Bob's growing string. Since the string 'S' repeats, you only need to track the index within a copy of 'S' and the number of copies used (the day).
Approach:
Algorithm:
O(N + M).
The precomputation of the 'next_occ' table takes O(N * 26), which simplifies to O(N) because 26 is a constant. The dynamic programming loop iterates M times. Inside the loop, operations like array lookups and assignments are O(1). Thus, the DP part takes O(M) time. The overall time complexity is dominated by these two parts, resulting in O(N + M).
O(N + M).
The 'next_occ' table requires O(N * 26) space, which simplifies to O(N). The DP table 'dp' requires O(M) space to store M pairs. Thus, the overall space complexity is of the order O(N + M).