




Sponsored
Sponsored
The Two-Pointer Technique involves maintaining two indices, one for each string (s and t). Start both pointers at the beginning of their respective strings. Move the pointer for 's' only when there's a match with the current character at 't'. This ensures that all characters in 's' appear in 't' with the correct order. If the pointer for 's' reaches the end of 's', then 's' is a subsequence of 't'.
Time Complexity: O(n) where n is the length of 't'.
Space Complexity: O(1) as no additional data structures are used.
1public boolean isSubsequence(String s, String t) {
2    int indexS = 0, indexT = 0;
3    while (indexS < s.length() && indexT < t.length()) {
4        if (s.charAt(indexS) == t.charAt(indexT)) {
5            indexS++;
6        }
7        indexT++;
8    }
9    return indexS == s.length();
10}The Java implementation also uses two indices to iterate through 's' and 't'. The matching logic determines if 's' is a subsequence by comparing individual characters and advancing the pointers appropriately.
For frequent 's' queries, preprocess 't' to build a map of character positions using a dictionary or hashmap structure. This allows for efficient binary search to determine if 's' is a subsequence, as only relevant sections of 't' need to be checked.
Preprocessing Time Complexity: O(n) for preparing the map where n is the length of 't'.
Checking Time Complexity: O(mlog(k)) for each 's', where m is the length of 's' and k is the average number of occurrences of each character in 't'.
Space Complexity: O(n) for the map storage.
1from collections import defaultdict
2from bisect import bisect_right
3
4def 
This Python solution uses a map to store positions of each character in 't'. For each character in 's', it performs a binary search using the 'bisect' module to locate the next valid position in 't'. This avoids full scans and enhances efficiency for large numbers of 's'.