LeetCode Problem -4 (Counting Words With a Given Prefix)

LeetCode Problem -4 (Counting Words With a Given Prefix)

Counting Words With a Given Prefix

Problem :

Imagine you have a list of words, like [“apple”, “banana”, “apricot”, “grape”]. Now, suppose someone asks you, “How many of these words start with ‘ap’?” You’d say “apple” and “apricot”, right? That’s exactly what we need to do in this problem, but using a computer program.

In technical terms, “ap” is called a “prefix” – a little piece of a word that comes at the beginning. Our task is to write a program that counts how many words in a list start with a specific prefix.

Example to Understand Better

Let’s look at an example to understand this better:

  • Our list of words (or “array of strings”) is [“pay”, “attention”, “practice”, “attend”].
  • We want to find out how many of these words start with “at”.

If you look closely, “attention” and “attend” start with “at”. So, the answer is 2.

Solution :

class Solution:
    def prefixCount(self, words, pref):
        count = 0
        for word in words:
            if word.startswith(pref):
                count += 1
        return count

Why Is This Useful?

Learning to solve problems like this is super useful because it helps you think logically and methodically. It’s not just about counting words; it’s about breaking down a problem into smaller steps and solving it bit by bit. This skill is handy in many areas, not just in programming!