Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created January 9, 2025 22:29
Show Gist options
  • Save Ifihan/e10147d8567a55b51377d3e4f14f782d to your computer and use it in GitHub Desktop.
Save Ifihan/e10147d8567a55b51377d3e4f14f782d to your computer and use it in GitHub Desktop.
Counting Words With a Given Prefix

Question

Approach

To solve the problem, I iterated directly over the list.Then I checked if the prefix pref matched the initial substring of the word. This was achieved by slicing the string word up to the length of pref and comparing it with pref. If they matched, I incremented a counter, which I returned at the end of the function.

Implemtation

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        count = 0

        for word in words:
            if word[:len(pref)] == pref:
                count += 1
        return count

Complexities

  • Time: O(n.m) where n is the number of strings in the words list and m is the length of the prefix pref.
  • Space: O(1).
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment