Understand Counting Words With a Given Prefix Problem

Problem Name: Counting Words With a Given Prefix
Problem Description:

Problem: Counting Words With a Given Prefix

Description:

You are given:

  • An array of strings words.
  • A string pref.

Your task is to count how many strings in words start with the prefix pref.

A prefix of a string s is defined as any leading contiguous substring of s. For example:

  • "pre" is a prefix of "prefix".
  • "ex" is a prefix of "example".

Return the count of strings in words that have pref as their prefix.


Examples:

Example 1:

Input:
words = ["apple", "apply", "application", "banana"]
pref = "app"

Output:
3

Explanation:
The strings that start with the prefix "app" are:

  • "apple"
  • "apply"
  • "application"

So, the result is 3.


Example 2:

Input:
words = ["cat", "car", "dog", "cart"]
pref = "ca"

Output:
3

Explanation:
The strings that start with the prefix "ca" are:

  • "cat"
  • "car"
  • "cart"

So, the result is 3.


Example 3:

Input:
words = ["hello", "world", "hi", "house"]
pref = "ho"

Output:
1

Explanation:
The only string that starts with the prefix "ho" is:

  • "house"

So, the result is 1.


Constraints:

  1. 1words.length1001 \leq \text{words.length} \leq 100
  2. 1words[i].length,pref.length1001 \leq \text{words[i].length}, \text{pref.length} \leq 100
  3. All strings in words\text{words} and pref\text{pref} consist of lowercase English letters.

Goal:

Write a function that takes the array words and the string pref as input and returns the count of strings in words that start with the prefix pref.

Category:
  • Leetcode Problem of the Day
  • Arrays
  • Strings
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/counting-words-with-a-given-prefix/description/

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

Main Function is not defined.

Helper Function:

INPUT : words = ["apple", "apply", "application", "banana"] , pref = "app"

OUTPUT: 3

public static int countWordsWithPrefix( String[] words , String pref) {

int count = 0;

for ( String word: words) {

if (word.strartsWith(pref)) {

count++;

}//If End

}//Loop End

return count;

} //function end;

Utility Functions and Global variables:

Utility Function is not required.