Talentd
FleetCode
Make and follow sheets.Sign in

Camelcase Matching solution and explanation

MediumArrayStringString MatchingTrie6 min read65.8% acceptanceUpdated 9 Apr 2026
1023. Camelcase Matching | LEETCODE MEDIUM | STRING MATCHINGcode Explainer · 6:39 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. 1023. Camelcase Matching | LEETCODE MEDIUM | STRING MATCHINGcode Explainer · 6:39 · 2K views
  2. Camelcase Matching (Leetcode 1023) Trie based solutionCoding Interviews · 14:47 · 1K views
  3. Camelcase Matching - How to Think and Solve || LeetCode 1023 || Python Solution || FAANGRelax and Code · 12:37 · 1K views
  4. Camelcase Matching (Leetcode 1023)Coding Interviews · 11:30 · 1K views
  5. Leetcode-1023. Camelcase MatchingRaman Bhari · 18:54 · 570 views
  6. 1023. Camelcase Matching (Leetcode Medium)Programming Live with Larry · 8:10 · 341 views
  7. 1023. Camelcase Matching | LEETCODE MEDIUM | STRING MATCHINGCodeWithMe · 9:05 · 189 views
  8. 猩猩的乐园 Leetcode 1023 Camelcase Matching猩猩的乐园 · 5:58 · 172 views
  9. (C#)LeetCode 1023 Camelcase Matchingzongwu yang · 20:53 · 107 views
  10. Camelcase Matching, Medium, LeetCode 1023H William Polenz · 15:31 · 39 views

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 pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.

Example 1:

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".
"FootBall" can be generated like this "F" + "oot" + "B" + "all".
"FrameBuffer" can be generated like this "F" + "rame" + "B" + "uffer".

Example 2:

Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
Output: [true,false,true,false,false]
Explanation: "FooBar" can be generated like this "Fo" + "o" + "Ba" + "r".
"FootBall" can be generated like this "Fo" + "ot" + "Ba" + "ll".

Example 3:

Input: queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
Output: [false,true,false,false,false]
Explanation: "FooBarTest" can be generated like this "Fo" + "o" + "Ba" + "r" + "T" + "est".

Constraints:

  • 1 <= pattern.length, queries.length <= 100
  • 1 <= queries[i].length <= 100
  • queries[i] and pattern consist of English letters.

Approach overview

Problem Overview: You receive a list of query strings and a camelCase pattern. A query matches the pattern if you can insert lowercase letters into the pattern to form the query without changing the order of the pattern’s characters. Any extra uppercase letter that does not appear in the pattern immediately invalidates the match.

The challenge is verifying that uppercase characters align exactly with the pattern while allowing extra lowercase characters anywhere. Each query must be checked independently, which makes careful character comparison the key part of the algorithm.

Approach 1: Two-Pointer Technique (O(q * n) time, O(1) space)

This approach scans each query and the pattern using two pointers. One pointer walks through the query while the other tracks the current position in the pattern. When characters match, both pointers advance. If the query character is lowercase and doesn't match, it can be skipped. If it is uppercase and doesn't match the pattern, the query immediately fails because uppercase letters cannot be inserted arbitrarily.

The key insight: uppercase letters must match exactly and in order, while lowercase letters act as "fillers" that can be ignored. You iterate through the query once, making the check linear for each query. This solution uses only constant extra memory and is typically the expected interview solution when working with two pointers and string processing.

Approach 2: Regular Expression Matching (O(q * n) time, O(n) space)

The pattern can be converted into a regular expression that enforces the camelCase constraints. For example, between every pattern character you allow any number of lowercase letters using [a-z]*. The regex becomes something like ^[a-z]*P[a-z]*a[a-z]*t[a-z]*... depending on the pattern characters. Each query is then tested against this compiled expression.

This approach is concise in languages with strong regex support such as Python or JavaScript. However, it introduces regex engine overhead and requires building the pattern dynamically. While the complexity remains linear relative to query length, the constant factors are higher than the manual scan.

Recommended for interviews: The Two-Pointer Technique is the expected solution. It demonstrates control over string traversal, conditional checks for uppercase characters, and constant-space design. Regex can be a quick implementation in production code, but interviewers generally prefer the explicit pointer-based logic because it clearly shows how you enforce the camelCase rules. The problem mainly tests string processing skills and pattern validation using ideas common in array traversal and pointer scanning.

Approach 1: Two-Pointer Technique

This approach uses a two-pointer technique to check if each query can match the pattern.

Traverse over both the query and pattern with a pointer for each. If the characters match, move both pointers; if not, just move the pointer of the query. The key is to ensure all uppercase letters in the query are matched by the pattern in order.

from typing import List

class Solution:
    def matches(self, query: str, pattern: str) -> bool:
        j = 0
        for c in query:
            if j < len(pattern) and c == pattern[j]:
                j += 1
            elif c.isupper():
                return False
        return j == len(pattern)

    def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:
        return [self.matches(query, pattern) for query in queries]
import java.util.*;

class Solution {
    public boolean matches(String query, String pattern) {
        int j = 0;
        for (char c : query.toCharArray()) {
            if (j < pattern.length() && c == pattern.charAt(j)) {
                j++;
            } else if (Character.isUpperCase(c)) {
                return false;
            }
        }
        return j == pattern.length();
    }
    public List<Boolean> camelMatch(String[] queries, String pattern) {
        List<Boolean> result = new ArrayList<>();
        for (String query : queries) {
            result.add(matches(query, pattern));
        }
        return result;
    }
}
#include <vector>
#include <string>

class Solution {
public:
    bool matches(const std::string& query, const std::string& pattern) {
        int j = 0;
        for (char c : query) {
            if (j < pattern.length() && c == pattern[j]) {
                ++j;
            } else if (isupper(c)) {
                return false;
            }
        }
        return j == pattern.length();
    }
    std::vector<bool> camelMatch(std::vector<std::string>& queries, std::string pattern) {
        std::vector<bool> result;
        for (const std::string& query : queries) {
            result.push_back(matches(query, pattern));
        }
        return result;
    }
};
var camelMatch = function(queries, pattern) {
    const matches = (query, pattern) => {
        let j = 0;
        for (const char of query) {
            if (j < pattern.length && char === pattern[j]) {
                j++;
            } else if (char >= 'A' && char <= 'Z') {
                return false;
            }
        }
        return j === pattern.length;
    };
    return queries.map(query => matches(query, pattern));
};
#include <stdbool.h>
#include <string.h>

bool matches(char* query, char* pattern) {
    int i = 0, j = 0;
    while (query[i]) {
        if (j < strlen(pattern) && query[i] == pattern[j]) {
            j++;
        } else if (query[i] >= 'A' && query[i] <= 'Z') {
            return false;
        }
        i++;
    }
    return j == strlen(pattern);
}

bool* camelMatch(char** queries, int queriesSize, char* pattern, int* returnSize) {
    *returnSize = queriesSize;
    bool* result = (bool*)malloc(queriesSize * sizeof(bool));
    for (int i = 0; i < queriesSize; i++) {
        result[i] = matches(queries[i], pattern);
    }
    return result;
}
using System;
using System.Collections.Generic;

public class Solution {
    public bool Matches(string query, string pattern) {
        int j = 0;
        foreach (char c in query) {
            if (j < pattern.Length && c == pattern[j]) {
                j++;
            } else if (char.IsUpper(c)) {
                return false;
            }
        }
        return j == pattern.Length;
    }

    public IList<bool> CamelMatch(string[] queries, string pattern) {
        List<bool> result = new List<bool>();
        foreach (string query in queries) {
            result.Add(Matches(query, pattern));
        }
        return result;
    }
}

The Python solution makes use of a helper function matches for matching logic. camelMatch uses a list comprehension to apply matches over each query.

Complexity

Time Complexity: O(n * m), where n is the number of queries and m is the average length of the queries.

Space Complexity: O(n), for storing the results.

Try this approach in the editor

Approach 2: Regular Expression Matching

This approach involves creating regular expressions from the patterns and matching them against each query directly.

Construct a regex pattern by translating the given pattern where each uppercase letter is preceded by a regex for any lowercase letters. We then apply this regex to each query.

import re

class Solution:
    def camelMatch(self, queries, pattern):
        regex_pattern = '^' + ''.join(c + '[a-z]*' for c in pattern) + '$'
        regex = re.compile(regex_pattern)
        return [bool(regex.match(query)) for query in queries]
var camelMatch = function(queries, pattern) {
    const regex = new RegExp(`^${pattern.split('').map(c => c + '[a-z]*').join('')}$`);
    return queries.map(query => regex.test(query));
};

In Python, build the regex pattern by adding [a-z]* after each character in the pattern. Use re module to compile and match against each query.

Complexity

Time Complexity: Depends on regex engine but generally O(n * m), where n is the number of queries and m is the average length of the queries.

Space Complexity: O(n), for storing results.

Try this approach in the editor

Approach 3: Two Pointers

We can traverse every string in queries and check whether it matches pattern or not. If it matches, we add true to the answer array, otherwise we add false.

Next, we implement a function check(s, t) to check whether the string s matches the string t.

We can use two pointers i and j to traverse the two strings. If the characters pointed to by i and j are not the same and s[i] is a lowercase letter, then we move the pointer i to the next position.

If the pointer i has reached the end of the string s or the characters pointed to by i and j are not the same, we return false. Otherwise, we move both pointers i and j to the next position. When the pointer j reaches the end of the string t, we need to check if the remaining characters in the string s are all lowercase letters. If so, we return true, otherwise we return false.

Time complexity (n times m), where n and m are the length of the array queries and the string pattern respectively.

function camelMatch(queries: string[], pattern: string): boolean[] {
    const check = (s: string, t: string) => {
        const m = s.length;
        const n = t.length;
        let i = 0;
        let j = 0;
        for (; j < n; ++i, ++j) {
            while (i < m && s[i] !== t[j] && s[i].codePointAt(0) >= 97) {
                ++i;
            }
            if (i === m || s[i] !== t[j]) {
                return false;
            }
        }
        while (i < m && s[i].codePointAt(0) >= 97) {
            ++i;
        }
        return i == m;
    };
    const ans: boolean[] = [];
    for (const q of queries) {
        ans.push(check(q, pattern));
    }
    return ans;
}
func camelMatch(queries []string, pattern string) (ans []bool) {
	check := func(s, t string) bool {
		m, n := len(s), len(t)
		i, j := 0, 0
		for ; j < n; i, j = i+1, j+1 {
			for i < m && s[i] != t[j] && (s[i] >= 'a' && s[i] <= 'z') {
				i++
			}
			if i == m || s[i] != t[j] {
				return false
			}
		}
		for i < m && s[i] >= 'a' && s[i] <= 'z' {
			i++
		}
		return i == m
	}
	for _, q := range queries {
		ans = append(ans, check(q, pattern))
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Two-Pointer Technique

Time Complexity: O(n * m), where n is the number of queries and m is the average length of the queries.

Space Complexity: O(n), for storing the results.

Regular Expression Matching

Time Complexity: Depends on regex engine but generally O(n * m), where n is the number of queries and m is the average length of the queries.

Space Complexity: O(n), for storing results.

Two Pointers–

Complexity analysis

ApproachTimeSpaceWhen to Use
Two-Pointer TechniqueO(q * n)O(1)Best general solution; efficient for iterating through each query and validating uppercase alignment
Regular Expression MatchingO(q * n)O(n)Useful when regex libraries are available and quick pattern construction is preferred

Frequently asked questions

Is Camelcase Matching easy or hard?

Camelcase Matching is generally rated Medium difficulty. The logic is straightforward once you recognize that uppercase letters must match exactly while lowercase letters can be skipped. The challenge lies in implementing the conditions cleanly during the two-pointer traversal.

Camelcase Matching Python/Java solution

In Python or Java, the typical implementation uses two pointers to iterate through the query and pattern strings. For each query, advance both pointers on matches, skip lowercase mismatches, and reject unmatched uppercase letters. The logic is identical across languages and runs in O(q * n) time.

How to solve Camelcase Matching in O(n)?

Process each query with a two-pointer scan against the pattern. Iterate through the query characters and compare them with the pattern pointer. Skip lowercase mismatches but reject any unmatched uppercase characters. Each query takes O(n) time because every character is examined once.

What is the best approach for Camelcase Matching?

The two-pointer technique is the best approach. You scan the query and pattern simultaneously, advancing the pattern pointer only when characters match. Lowercase characters in the query can be skipped, but any unmatched uppercase letter invalidates the match. This approach runs in O(q * n) time with O(1) extra space.

Is Camelcase Matching asked at Google/Amazon/Meta?

Camelcase Matching represents a common string pattern-matching problem similar to questions asked at companies like Google, Amazon, and Meta. It tests careful string traversal, handling uppercase constraints, and writing clean validation logic using pointers.

What data structure is used in Camelcase Matching?

The problem mainly relies on string traversal and pointer manipulation rather than complex data structures. The standard solution uses two pointers over strings. Conceptually, the queries can be viewed as arrays of characters processed sequentially.

What is the time complexity of Camelcase Matching?

The optimal solution runs in O(q * n) time where q is the number of queries and n is the average query length. Each query is scanned once using two pointers. Space complexity is O(1) because only a few pointer variables are used.

Comments

Now write it yourselfClose this page and solve Camelcase Matching in the editor, without looking.
Practise Camelcase Matching