Taro Logo

Is Subsequence

#187 Most AskedEasy
0 views
Topics:
StringsTwo PointersDynamic ProgrammingBinary SearchGreedy Algorithms

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = "abc", t = "ahbgdc"
Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"
Output: false

Constraints:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 104
  • s and t consist only of lowercase English letters.
Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum possible length of strings $s$ and $t$?
  2. What character set do the strings $s$ and $t$ consist of? Are we dealing only with lowercase English letters, or can they include uppercase letters, digits, or Unicode/ASCII characters?
  3. How should empty strings be handled? For instance, is an empty string $s$ considered a subsequence of any string $t$ (including an empty string $t$)?
  4. Can string $s$ be longer than string $t$, and if so, should it immediately return false?
  5. If $s$ and $t$ are identical, should the function return true?

Brute Force Solution

Approach

Imagine you are trying to find a hidden secret word inside a much larger text by crossing out letters you do not need. The brute force approach tries every possible way to match up pieces of the smaller word against the larger text to see if it can be built correctly.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first letter of the smaller word and search through the larger text until you find a matching letter.
  2. Once found, mark that position and move on to the next letter of the smaller word.
  3. Keep searching through the remainder of the larger text for this new letter, trying every possible match if there are multiple identical letters around.
  4. Repeat this process for every single letter in the smaller word in their exact order.
  5. If you successfully manage to find matching letters for the entire smaller word without ever having to jump backwards in the larger text, then you have confirmed the match.
  6. If you run out of text before finishing the smaller word, realize that this particular path failed.
  7. Because this is the brute force strategy, if one path gets stuck, mentally reset and try starting your search from different matching spots earlier in the text to see if another combination works.

Code Implementation

def is_subsequence_brute_force(target_word, source_text):
    # We explore all potential starting positions in the text to ensure we do not miss any valid match
    for start_position in range(len(source_text) - len(target_word) + 1):
        text_pointer = start_position
        target_pointer = 0
        
        # We iterate through the text to match each character of the target word sequentially
        while text_pointer < len(source_text) and target_pointer < len(target_word):
            if source_text[text_pointer] == target_word[target_pointer]:
                target_pointer += 1
            text_pointer += 1
            
        # If all characters matched in order, we have successfully verified the subsequence
        if target_pointer == len(target_word):
            return True
            
    return False

Big(O) Analysis

Time Complexity
O(n * m) – In the worst-case scenario of this brute force strategy, for each of the n characters in the smaller word, we may have to scan through a significant portion of the m characters in the larger text to try multiple matching paths. When duplicate letters force us to explore alternative starting points and re-scan overlapping segments, the number of operations multiplies. This leads to approximately n * m operations in the absolute worst-case backtracking scenario, which simplifies to O(n * m).
Space Complexity
O(1) – The algorithm relies entirely on a few primitive pointers or index variables to track positions within the strings without storing any extra data structures. As the input sizes grow, no additional memory is allocated for temporary lists, hash maps, or recursive call stacks. Therefore, the auxiliary space remains constant regardless of the lengths of the strings.

Optimal Solution

Approach

To check if a shorter word appears inside a longer sentence in the exact same order, the best strategy is to walk through the sentence from beginning to end while ticking off letters of the shorter word as you find them. This works because we only care about the relative order of the letters, allowing us to scan the sentence just once.

Here's how the algorithm would work step-by-step:

  1. Stand at the very beginning of both the short word and the long sentence.
  2. Look at the current letter in the long sentence and see if it matches the letter you are currently trying to find from the short word.
  3. If they match, consider that letter found and immediately shift your focus to the next letter in the short word.
  4. Regardless of whether there was a match, always take a step forward in the long sentence to look at the next letter.
  5. Keep repeating this process of scanning the sentence until you either run out of letters in the sentence or successfully find every letter of the short word.
  6. If you successfully tick off every single letter of the short word before the sentence ends, then the short word is indeed hidden inside the sentence in the correct order.

Code Implementation

class Solution:
    def isSubsequence(self, short_word: str, long_sentence: str) -> bool:
        pointer_short = 0
        pointer_long = 0
        
        # We iterate through the long sentence to check characters in order.
        while pointer_short < len(short_word) and pointer_long < len(long_sentence):
            if short_word[pointer_short] == long_sentence[pointer_long]:
                pointer_short += 1
            
            pointer_long += 1
        
        # If we reached the end of the short word, all characters were found.
        return pointer_short == len(short_word)

Big(O) Analysis

Time Complexity
O(n) – The time complexity is driven by a single pass through the characters of the long sentence, where n represents the length of that sentence. As we iterate from the beginning to the end of the sentence, we perform constant-time comparisons and potentially advance our pointer through the short word. We examine each character in the sentence at most once without needing to revisit any previous elements. This sequential scanning process results in approximately 1 * n operations, which simplifies to O(n).
Space Complexity
O(1) – To check if the short word is a subsequence, the algorithm only maintains two integer pointers to track the current index in the short word and the long sentence. These pointer variables consume a constant amount of memory regardless of the input lengths. No auxiliary data structures, temporary lists, or recursion stack frames are allocated during execution. Therefore, the extra memory required remains entirely fixed as the input size grows.

Edge Cases

String s is empty
How to Handle:
An empty string is trivially a subsequence of any string t, so the two pointer approach will immediately return true.
String t is empty while s is not empty
How to Handle:
Since t has no characters to match s, the pointers will exhaust t and correctly return false.
Both strings s and t are empty
How to Handle:
An empty s is a subsequence of an empty t, resulting in an immediate true return value.
String s is longer than string t
How to Handle:
A longer string cannot be a subsequence of a shorter one, and the pointer logic will finish without matching all of s, returning false.
Strings contain identical characters or are identical
How to Handle:
The two pointers will advance in lockstep through both strings until s is fully matched, returning true.
String t contains many interleaving or distractor characters
How to Handle:
The algorithm simply skips over characters in t that do not match the current character of s until a match is found or t ends.
Very large strings s and t up to constraints
How to Handle:
The linear time complexity O(n) and constant space complexity O(1) two pointer approach easily handles maximum constraints without stack overflow or memory limits.
Unicode characters or multi-byte strings
How to Handle:
Most language runtimes handle character iteration properly, but care must be taken with code points versus code units if indices cross multi-byte boundaries.
0/257 completed