Camelcase Matching — LeetCode 1023 Python Solution

MediumTrieArrayTwo PointersStringString Matching
Problem
#1023
Pattern
Trie
Reading time
3 min

The problem

Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise. A query word queries[i] matches pattern if you can insert lowercase English letters into the pattern so that it equals the query.

Example

Input
queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
Output
[true,false,true,true,false]
Explanation
"FooBar" can be generated like this "F" + "oo" + "B" + "ar".

Python solution

Python
class Solution:
    def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:
        def check(s, t):
            m, n = len(s), len(t)
            i = j = 0
            while j < n:
                while i < m and s[i] != t[j] and s[i].islower():
                    i += 1
                if i == m or s[i] != t[j]:
                    return False
                i, j = i + 1, j + 1
            while i < m and s[i].islower():
                i += 1
            return i == m

        return [check(q, pattern) for q in queries]

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(1) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 1023. Camelcase Matching is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Trie.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1023. Camelcase Matching?
LeetCode 1023. Camelcase Matching is rated Medium on LeetCode.
What is the time complexity of LeetCode 1023. Camelcase Matching?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
What is the space complexity of LeetCode 1023. Camelcase Matching?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1023. Camelcase Matching cover?
LeetCode 1023. Camelcase Matching is tagged Trie, Array, Two Pointers, String and String Matching on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview