Is Subsequence

easy Strings

Problem

Two words are given: a pattern and a text. Print true if you can delete some letters from the text (without changing the order of the others) to get the pattern. Print false otherwise.

Constraints

  • 1 <= length <= 10^5

Examples

Input

ace abcde

Output

true

Input

aec abcde

Output

false

Solutions

Best approachTime O(n)Space O(1)

A greedy walk is enough: take the first possible match for each pattern letter. A subsequence keeps the order but may skip letters, unlike a substring.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Check subsequence.
 * Input   : A pattern and a text.
 * Output  : true or false.
 * Approach: Two pointers.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static boolean solve(String a, String b) {
        // Step 1: i points to the next letter of the pattern we are looking for.
        int i = 0;

        // Step 2: Walk through the text once. When a letter matches, move to the next pattern letter.
        for (int j = 0; j < b.length() && i < a.length(); j++) {
            if (a.charAt(i) == b.charAt(j)) {
                i++;
            }
        }

        // Step 3: If we matched every letter of the pattern, it is a subsequence.
        return i == a.length();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. What is the difference between a substring and a subsequence?