Drill

ProblemsC++ › patterns

Did they type the letters in order

easypatternsTwo pointersStringsC++

A command palette matches what someone typed against a command name: the letters have to appear in order, but not next to each other.

typedInOrder(typed: string, command: string) → bool

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

bool typedInOrder(std::string typed, std::string command) {
    
}

Worked examples

CallResult
typedInOrder(std::string("abc"), std::string("axbxc"))true
typedInOrder(std::string("acb"), std::string("axbxc"))false
typedInOrder(std::string(""), std::string("anything"))true
typedInOrder(std::string("abc"), std::string("abc"))true

Hint

One index walks the typed text, one walks the command. Advance the command index every step, and the typed index only when the two characters agree.

Reference solution in C++
bool typedInOrder(std::string typed, std::string command) {
    size_t i = 0;
    for (char ch : command) {
        if (i < typed.size() && typed[i] == ch) i++;
    }
    return i == typed.size();
}

The same problem in another language

More patterns problems in C++