Count Prefixes of a Given String — LeetCode 2255 Python Solution

EasyArrayString
Problem
#2255
Pattern
Hash Map
Reading time
2 min

The problem

You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s.

Example

Input
words = ["a","b","c","ab","bc","abc"], s = "abc"
Output
3
Explanation
The strings in words which are a prefix of s = "abc" are:

Python solution

Python
class Solution:
    def countPrefixes(self, words: List[str], s: str) -> int:
        return sum(s.startswith(w) for w in words)

Complexity

MeasureComplexity
TimeO(m \times n), where m and n are the lengths of the array words and the string s, respectively
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2255. Count Prefixes of a Given String is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2255. Count Prefixes of a Given String?
LeetCode 2255. Count Prefixes of a Given String is rated Easy on LeetCode.
What is the time complexity of LeetCode 2255. Count Prefixes of a Given String?
The Python solution on this page runs in O(m \times n), where m and n are the lengths of the array words and the string s, respectively.
What is the space complexity of LeetCode 2255. Count Prefixes of a Given String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2255. Count Prefixes of a Given String cover?
LeetCode 2255. Count Prefixes of a Given String is tagged Array and String 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