question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
count-nodes-equal-to-average-of-subtree
Simple Clean Code With Description C++
simple-clean-code-with-description-c-by-smm0y
\n# Approach\n We want to use dfs to traverse the tree and while traversing we want to know the average at the each node and when we backtrack we will use the a
SSS009
NORMAL
2022-12-12T04:21:49.425188+00:00
2022-12-27T18:57:58.731036+00:00
357
false
\n# Approach\n We want to use dfs to traverse the tree and while traversing we want to know the average at the each node and when we backtrack we will use the averages of already calculated averages of the children of the node and use them to calculate the average of the root node.\n\n We carry forward the values sum and the no of nodes with the help of value pair to help us calulate the average and to compare the average is equal to value of the root. If it is equal we increase the count by 1.\n\n# Complexity\n- Time complexity:\n Time complexity of this approach(D.F.S) is O(n) where n is the number of nodes in the given tree.\n\n Upvote if you find it helpful.\n\n\n# Code\n```\nclass Solution {\npublic:\nint count = 0;\n int averageOfSubtree(TreeNode* root) {\n average(root);\n return count;\n }\nint avg,sum,no_of_nodes;\n pair<int,int> average(TreeNode* root){\n if (root == NULL){\n return make_pair(0, 0);\n }\n pair<int,int> left = average(root->left);\n pair<int,int> right = average(root->right);\n sum = (left.first + right.first + root->val);\n no_of_nodes = (left.second + right.second + 1);\n avg = sum/(no_of_nodes);\n if (root->val == avg){\n count++;\n }\n return make_pair(sum, no_of_nodes);\n }\n};\n```
2
0
['Tree', 'Depth-First Search', 'C++']
0
count-nodes-equal-to-average-of-subtree
Fast recursion solution with notes by Java & Javascript ✅
fast-recursion-solution-with-notes-by-ja-5f7d
java\n\n\nclass Solution {\n \n int res = 0;\n \n public int averageOfSubtree(TreeNode root) {\n node t = new node(0,0);\n counting(ro
MJWHY
NORMAL
2022-11-13T13:47:01.424952+00:00
2022-11-13T13:47:01.424994+00:00
829
false
**java**\n![image](https://assets.leetcode.com/users/images/3fb5d04d-9c49-4c61-8518-151fd1a13403_1668347151.616631.png)\n```\nclass Solution {\n \n int res = 0;\n \n public int averageOfSubtree(TreeNode root) {\n node t = new node(0,0);\n counting(root);\n return res;\n }\n \n // recursion method : \n private node counting(TreeNode root){\n \n // base case :\n if(root.left == null && root.right == null){\n node temp = new node(root.val,1);\n res++;\n return temp;\n }\n node tempLeft = new node(0,0);\n node tempRight = new node(0,0);\n \n // first check left :\n if(root.left != null){\n tempLeft = counting(root.left);\n }\n \n // check right :\n if(root.right != null){\n tempRight = counting(root.right);\n }\n \n // sum = values of nodes :\n int sum = tempLeft.sum + tempRight.sum + root.val;\n // count = number of nodes :\n int count = tempLeft.count + tempRight.count + 1;\n \n if(sum/count == root.val) res++;\n \n // return the node :\n node temp = new node(sum,count);\n return temp;\n }\n \n}\n\nclass node{\n int sum = 0;\n int count = 0;\n \n node(int s, int c){\n sum = s;\n count = c;\n }\n}\n```\n\n**Javascript**\n![image](https://assets.leetcode.com/users/images/b71dd70a-e898-4cc2-9ab3-849948723982_1668347194.1284957.png)\n```\nvar averageOfSubtree = function(root) {\n let res = 0;\n \n // recursion method : \n var counting = function(node){\n \n // base case :\n if(!node.left && !node.right){\n let tempArr = [node.val,1];\n res++;\n return tempArr;\n }\n \n let tempLeft = [0,0];\n let tempRight = [0,0];\n \n // check left :\n if(node.left){\n tempLeft = counting(node.left);\n }\n \n // check right :\n if(node.right){\n tempRight = counting(node.right);\n }\n \n // sum = values of nodes :\n let sum = tempLeft[0] + tempRight[0] + node.val;\n // count = number of nodes :\n let count = tempLeft[1] + tempRight[1] + 1;\n \n if(Math.floor(sum/count) == node.val) res++;\n \n // return array :\n let temp = [sum,count];\n return temp;\n }\n \n \n counting(root);\n return res;\n};\n```
2
0
['Recursion', 'Java', 'JavaScript']
0
count-nodes-equal-to-average-of-subtree
🚀🚀C++ Easy to understand solution ✨🚀🚀
c-easy-to-understand-solution-by-shxbh-eskk
I have made 2 extra function apart from main fxn\n1. to get the average of an subtree by passing root\n2. to get the number of nodes who have avg value = their
shxbh
NORMAL
2022-10-18T10:29:07.679650+00:00
2022-10-18T10:31:12.184456+00:00
249
false
**I have made 2 extra function apart from main fxn**\n1. to get the average of an subtree by passing root\n2. to get the number of nodes who have avg value = their root value \n```\n\nclass Solution {\npublic:\n void avgof(TreeNode* root, int &sum, int &cnt){\n if(root == NULL) {\n return;\n }\n sum = sum + root->val;\n cnt++;\n avgof(root->left, sum, cnt);\n avgof(root->right, sum, cnt);\n \n }\n void task(TreeNode* root,int &sum, int &cnt, int &ans ){\n if(root == NULL)return;\n sum =0;\n cnt =0;;\n avgof(root, sum, cnt);\n int k = sum / cnt;\n if(k == root->val)ans++; \n task(root->left, sum, cnt, ans);\n task(root->right, sum, cnt, ans);\n\n }\n int averageOfSubtree(TreeNode* root) {\n int sum, cnt, ans = 0;\n task(root, sum, cnt, ans);\n return ans;\n \n }\n};
2
0
['Tree']
0
count-nodes-equal-to-average-of-subtree
Simple Recursion
simple-recursion-by-rishantchauhan-5i3o
/\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode left;\n * TreeNode right;\n * TreeNode() : val(0), left
rishantchauhan
NORMAL
2022-10-07T12:39:40.845231+00:00
2022-10-07T12:40:41.415573+00:00
670
false
/**\n * Definition for a binary tree node.\n * struct TreeNode {\n * int val;\n * TreeNode *left;\n * TreeNode *right;\n * TreeNode() : val(0), left(nullptr), right(nullptr) {}\n * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n int count=0;\n int countnodes(TreeNode* root)\n {\n if(!root)\n return 0;\n else{\n return countnodes(root->left)+countnodes(root->right)+1;\n }\n }\n int findSum(TreeNode* root)\n {\n if(!root)\n return 0;\n return findSum(root->left)+findSum(root->right)+root->val;\n }\n int averageOfSubtree(TreeNode* root) {\n if(!root) \n return 0;\n if((findSum(root)/countnodes(root))==root->val)\n count++;\n averageOfSubtree(root->left);\n averageOfSubtree(root->right);\n \n return count;\n \n \n }\n \n};
2
0
['Recursion', 'C']
0
count-nodes-equal-to-average-of-subtree
C++ easy recursive solution
c-easy-recursive-solution-by-sahil_k_027-nv3n
See more in my GitHub repo LeetCode.\n\nRecuirsive Solution\nWe will use pair,avg> to store ans...And keep a count\nFor any node with avg == root->val count++\n
SahilK-027
NORMAL
2022-10-06T15:06:26.142677+00:00
2022-10-06T15:06:26.142720+00:00
29
false
See more in my GitHub repo [LeetCode](http://github.com/SahilK-027/LeetCode).\n\n**Recuirsive Solution**\nWe will use pair<pair<sum,number>,avg> to store ans...And keep a count\nFor any node with avg == root->val count++\n```\nclass Solution {\nprivate:\n pair<pair<int,int>,int> solve(TreeNode* root, int& count){\n //Base case\n if(root == NULL){\n pair<int,int> a = make_pair(0,0);\n pair<pair<int,int>,int> p = make_pair(a,0);\n return p;\n }\n // Recursive Call\n pair<pair<int,int>,int> leftAns = solve(root->left,count);\n pair<pair<int,int>,int> rightAns = solve(root->right,count);\n \n int sum = leftAns.first.first + rightAns.first.first + root->val;\n int n = 1 + leftAns.first.second + rightAns.first.second;\n int avg = sum / n;\n if(avg == root->val){\n count = count+1;\n }\n \n pair<pair<int,int>,int> ans;\n ans.first.first = sum;\n ans.first.second = n;\n ans.second = avg;\n return ans;\n \n }\npublic:\n int averageOfSubtree(TreeNode* root) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n int count = 0; \n pair<pair<int,int>,int> ans = solve(root,count);\n return count;\n }\n};\n```
2
0
['Recursion', 'C']
0
count-nodes-equal-to-average-of-subtree
C++ Easy Understanding | Recursive Solution
c-easy-understanding-recursive-solution-qossl
\nclass Solution {\npublic:\n void findSum(TreeNode* root, int &totalSum, int &count)\n {\n if(root == NULL) \n return;\n \n
dheerajkarwasra
NORMAL
2022-09-30T19:03:05.172712+00:00
2022-10-01T16:20:56.917960+00:00
403
false
```\nclass Solution {\npublic:\n void findSum(TreeNode* root, int &totalSum, int &count)\n {\n if(root == NULL) \n return;\n \n totalSum += root->val;\n count++;\n \n findSum(root->left, totalSum, count);\n findSum(root->right, totalSum, count);\n }\n \n \n int averageOfSubtree(TreeNode* root) \n {\n if(root == NULL) \n return 0;\n int countNodes = 0;\n int totalSum = 0;\n int count = 0;\n findSum(root, totalSum, count);\n int avg = totalSum/count;\n if(avg == root->val) \n countNodes++;\n return countNodes + averageOfSubtree(root->left) + averageOfSubtree(root->right);\n }\n};\n```
2
0
['Recursion', 'C']
0
count-nodes-equal-to-average-of-subtree
c solution
c-solution-by-nameldi-w9oh
\nint countOfSubtree(struct TreeNode* root, int* ans){\n if(!root) return 0;\n \n int left = countOfSubtree(root->left, ans);\n int right = countOfS
nameldi
NORMAL
2022-09-16T06:52:33.970741+00:00
2022-09-16T06:52:33.970780+00:00
62
false
```\nint countOfSubtree(struct TreeNode* root, int* ans){\n if(!root) return 0;\n \n int left = countOfSubtree(root->left, ans);\n int right = countOfSubtree(root->right, ans);\n\n int currCnt = left + right + 1;\n int currSum = root->val;\n currSum += (root->left)?root->left->val : 0;\n currSum += (root->right)?root->right->val : 0;\n \n if(root->val == (currSum / currCnt))\n (*ans)++;\n root->val = currSum;\n return currCnt;\n}\n\nint averageOfSubtree(struct TreeNode* root){\n int ans = 0;\n countOfSubtree(root, &ans);\n return ans;\n}\n```
2
0
['C']
0
count-nodes-equal-to-average-of-subtree
C++ || EASY || FULLY COMMENTED
c-easy-fully-commented-by-vish_30-ibyt
```\n int cnt=0;\n //pair of sum of subtree,numbr of nodes in the subtree is being used here\n pair slv(TreeNoderoot)\n {\n // if root is null
vish_30
NORMAL
2022-08-23T15:24:24.961325+00:00
2022-08-23T15:24:24.961364+00:00
302
false
```\n int cnt=0;\n //pair of sum of subtree,numbr of nodes in the subtree is being used here\n pair<int,int> slv(TreeNode*root)\n {\n // if root is null then sum and nmbr of nodes .. both are 0\n if(!root)\n return {0,0};\n //get data from left subtree\n pair<int,int>l=slv(root->left);\n //get data from right subtree\n pair<int,int>r=slv(root->right);\n //calculate nmbr of nodes from left and right subtrees data \n int n=l.second+r.second+1;\n //calculate the sum of the complete subtree i.e root+left tree + right tree\n int sum=l.first+r.first+root->val;\n //if root\'s value is equal to avg then increase count\n if(root->val==sum/n)\n cnt++;\n //return the sum and the nmbr of nodes calculated \n return {sum,n};\n }\n \n int averageOfSubtree(TreeNode* root) {\n slv(root);\n return cnt;\n }
2
0
['Tree', 'Depth-First Search', 'Recursion', 'C', 'Binary Tree', 'C++']
0
count-nodes-equal-to-average-of-subtree
Python: Simple Recursive Solution
python-simple-recursive-solution-by-anon-jvs4
Time Complexity: O(n) (We need to visit all n nodes)\nSpace Complexity: O(n) In the worst case the tree will look like a damn linked list and our recursion stac
anonta
NORMAL
2022-08-08T15:33:38.880716+00:00
2022-08-08T15:33:38.880747+00:00
300
false
**Time Complexity:** `O(n)` (We need to visit all n nodes)\n**Space Complexity:** `O(n)` In the worst case the tree will look like a damn linked list and our recursion stack will grow to n frames by the time we reach the leaf node.\n\n## Solution\n```\nclass Solution:\n def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n self.matchCount = 0\n \n self.explore(root)\n \n return self.matchCount\n \n def explore(self, root):\n if root is None:\n return 0, 0\n \n ls, lc = self.explore(root.left)\n rs, rc = self.explore(root.right)\n \n childTotal = ls + rs + root.val\n childCount = lc + rc + 1\n \n if childCount != 0 and root.val == childTotal // childCount:\n self.matchCount += 1\n \n return childTotal, childCount\n\n```
2
0
['Recursion', 'Python']
0
count-nodes-equal-to-average-of-subtree
Simple C++ Using Basic Recursive Functions
simple-c-using-basic-recursive-functions-rovn
\t\t\t\t\t\t\t\t#Vote if u like\u2764\uFE0F\n\t\tTo_Do:\n\t\t\t1.For this question we need to have sum , no.of nodes in subtree than need to find the average \n
Yashwanth_Yash_
NORMAL
2022-08-07T14:59:09.553721+00:00
2022-08-07T14:59:09.553768+00:00
147
false
\t\t\t\t\t\t\t\t#Vote if u like\u2764\uFE0F\n\t\tTo_Do:\n\t\t\t1.For this question we need to have sum , no.of nodes in subtree than need to find the average \n\t\t\t2.Than we need to check the value of the root and the average if same increment the count\n\t\t\t\n\t\tProcess:\n\t\t\t1. Need to create a function by which we can get the sum of the nodes under it \n\t\t\t2. Need to create a function so we can get the count of nodes \n\t\t\t3. Than need to traverse the tree and find the average by using the above funtions\n\t\t\t\n\t Code:\t\n\t\t \n\t\t\tclass Solution {\n\t\t\tpublic:\n\t\t\t\tint SumofNode(TreeNode *root) //Funtion to get Sum\n\t\t\t\t{\n\t\t\t\t\tif(root == NULL) return 0; //Tree empty return 0;\n\t\t\t\t\tint left = SumofNode(root -> left); //Left subtree will give ans to parent\n\t\t\t\t\tint right = SumofNode(root -> right); // Right subtree will give ans to parent\n\t\t\t\t\treturn left + right + root -> val; //We need to add root val also\n\t\t\t\t}\n\t\t\t\tint CountofNode(TreeNode *root)\n\t\t\t\t{\n\t\t\t\t\tif(root == NULL) return 0; //Tree empty return 0;\n\t\t\t\t\tint left = CountofNode(root -> left);//Left subtree will give ans to parent\n\t\t\t\t\tint right = CountofNode(root -> right);// Right subtree will give ans to parent\n\t\t\t\t\treturn left + right + 1;//We need to count root also\n\t\t\t\t}\n\t\t\t\tvoid fun(TreeNode *root , vector<pair<int , int>>&m)\n\t\t\t\t{\n\t\t\t\t\tif(root == NULL) return; //Tree empty return \n\t\t\t\t\tint x = SumofNode(root); //Sum of root\n\t\t\t\t\tint y = CountofNode(root); //no.of roots\n\t\t\t\t\tm.push_back({root -> val , (x * 1.0 / y)}); //Storing in vector\n\t\t\t\t\tfun(root -> left , m); //Passing the left root\n\t\t\t\t\tfun(root -> right , m);//PAssing the right root\n\t\t\t\t}\n\t\t\t\tint averageOfSubtree(TreeNode* root) {\n\t\t\t\t\tif(root == NULL) return 0; //Tree empty return 0;\n\t\t\t\t\tint count = 0;\n\t\t\t\t\tvector<pair<int , int>> m; //list to store the values\n\t\t\t\t\tfun(root , m);//Calling the function to get the values to vector\n\t\t\t\t\tfor(auto p: m)// Checking the root val and avg val if same increment count\n\t\t\t\t\t\tif(p.first == p.second) count++;\n\t\t\t\t\treturn count;//Return count\n\t\t\t\t}\n\t\t\t};\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-Yash:)\n\t\t\t\n\t\t\t
2
0
['Recursion', 'C', 'C++']
0
count-nodes-equal-to-average-of-subtree
c++ || O(N) || faster than 98% || EASY TO UNDERSTAND
c-on-faster-than-98-easy-to-understand-b-xtk9
class Solution {\npublic:\n int count=0;\n pair average(TreeNode root)\n {\n if(root==NULL)\n {\n pair p=make_pair(0,0);\n
charadiyahardip
NORMAL
2022-06-20T04:26:02.290362+00:00
2022-06-20T04:26:02.290402+00:00
209
false
class Solution {\npublic:\n int count=0;\n pair<int,int> average(TreeNode* root)\n {\n if(root==NULL)\n {\n pair<int,int> p=make_pair(0,0);\n return p;\n }\n \n pair<int,int> left=average(root->left);\n pair<int,int> right=average(root->right);\n \n int sum=left.first+right.first+root->val;\n int num=left.second+right.second+1;\n \n if(sum/num==root->val)\n count++;\n pair<int,int> ans;\n ans.first=sum;\n ans.second=num;\n return ans;\n }\n int averageOfSubtree(TreeNode* root) {\n average(root);\n return count;\n }\n};``
2
0
['Recursion', 'C', 'C++']
0
counting-words-with-a-given-prefix
Simple | Trie ->2 Approach Detailed Explanation
simple-5-lines-detailed-expalation-by-su-fhvi
🌟 Count Prefix MatchesIn this problem, you are given an array of strings words and a string pref. The task is to return the number of strings in words that cont
Sumeet_Sharma-1
NORMAL
2025-01-09T00:02:05.318350+00:00
2025-01-10T00:40:44.633099+00:00
11,816
false
# 🌟 Count Prefix Matches In this problem, you are given an array of strings `words` and a string `pref`. The task is to return the number of strings in `words` that contain `pref` as a prefix. A **prefix** refers to the beginning part of a string. # Channel https://www.youtube.com/@Sumeet_Sharma-1 # # Telegram https://t.me/leetmath # # 10 jan Simple Solution : [SOlUTION](https://leetcode.com/problems/word-subsets/solutions/6257553/memset-max-freq-detailed-explanation-solution/) # --- ## 🧠 Intuition A **prefix** is the starting substring of a given string. To solve the problem: 1. We will iterate through the list of strings in `words`. 2. For each string, we will check if it starts with the given prefix `pref`. 3. We will count how many strings in the array match the prefix condition. ### Example: - For the string `"pay"` and the prefix `"at"`, we check if `"pay"` starts with `"at"`. It does NOt , so it's not a match. - For the string `"attention"` and the prefix `"at"`, we check if `"attention"` starts with `"at"`. It does, so it's a match. - For the string `"practice"` and the prefix `"at"`, we check if `"practice"` starts with `"at"`. It does NOt , so it's not a match. - For the string `"attend"` and the prefix `"at"`, we check if `"attend"` starts with `"at"`. It does, so it's a match. ![Screenshot 2025-01-09 082841.png](https://assets.leetcode.com/users/images/b166cb38-6dbd-4c51-a36c-4464e6ba5c0b_1736391553.0079782.png) --- ## 🛠️ Approach Here’s how to approach solving the problem step-by-step: 1. **Iterate Through the Array**: - Loop through each string in the `words` array. 2. **Check for Prefix**: - For each string, check if it starts with the given prefix `pref`. - In Python, you can use the built-in method `startswith()`. Other languages have similar methods or you can manually compare the first characters. 3. **Count Matches**: - Maintain a counter variable to track how many words start with the prefix `pref`. - Every time a match is found, increment the counter by 1. 4. **Return Result**: - After checking all words, return the final count of prefix matches. --- ## 📊 Complexity ### Time Complexity: - **O(n * m)** - \(n\) is the number of words in the array. - \(m\) is the average length of each word. - For each word, checking the prefix using `startswith()` takes \(O(m)\) time. ### Space Complexity: - **O(1)** - We only use a counter variable for storing the result, so the space complexity is constant. --- ![9c6f9412-c860-47d6-9a2e-7fcf37ff3321_1686334926.180891.png](https://assets.leetcode.com/users/images/7bef5edb-22b2-44df-862d-4f0a3ad31c2a_1736381622.5732725.png) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; for (const string& word : words) { if (word.find(pref) == 0) { count++; } } return count; } }; ``` ```Java [] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (String word : words) { if (word.startsWith(pref)) { count++; } } return count; } } ``` ```Python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: count = 0 for word in words: if word.startswith(pref): count += 1 return count ``` ```C [] int prefixCount(char** words, int wordsSize, char* pref) { int count = 0; for (int i = 0; i < wordsSize; i++) { if (strncmp(words[i], pref, strlen(pref)) == 0) { count++; } } return count; } ``` ```C# [] public class Solution { public int PrefixCount(string[] words, string pref) { int count = 0; foreach (string word in words) { if (word.StartsWith(pref)) { count++; } } return count; } } ``` ```Javascript [] /** * @param {string[]} words * @param {string} pref * @return {number} */ var prefixCount = function(words, pref) { let count = 0; for (let word of words) { if (word.startsWith(pref)) { count++; } } return count; }; ``` # Trie Aproch # ```C++ [] class Node { public: Node* children[26]; int count; Node() { for (int i = 0; i < 26; i++) { children[i] = nullptr; } count = 0; } }; class PrefixTree { private: Node* root; public: PrefixTree() { root = new Node(); } void addWord(const string& word) { Node* current = root; for (char ch : word) { int index = ch - 'a'; if (current->children[index] == nullptr) { current->children[index] = new Node(); } current = current->children[index]; current->count++; } } int getPrefixCount(const string& prefix) { Node* current = root; for (char ch : prefix) { int index = ch - 'a'; if (current->children[index] == nullptr) { return 0; } current = current->children[index]; } return current->count; } }; class Solution { public: int prefixCount(vector<string>& words, string prefix) { PrefixTree tree; for (const string& word : words) { tree.addWord(word); } return tree.getPrefixCount(prefix); } }; ```
55
3
['Trie', 'C', 'String Matching', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
11
counting-words-with-a-given-prefix
✅Easy to understand✅ Beats 100%
easy-to-understand-beats-100-by-hema2607-tnrn
Code
20250409.hema260706
NORMAL
2025-01-09T02:27:17.450015+00:00
2025-01-09T02:27:17.450015+00:00
10,784
false
![image.png](https://assets.leetcode.com/users/images/0e4280a3-55d3-4d5d-9e18-b0177c3060f4_1736389313.9701693.png) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c = 0; int n = pref.length(); for (const string& w : words) { if (w.size() >= n && w.compare(0, n, pref) == 0) { c++; } } return c; } }; ``` ```python [] class Solution: def prefixCount(self, words: list[str], pref: str) -> int: c = 0 n = len(pref) for word in words: if len(word) >= n and word[:n] == pref: c += 1 return c ``` ```Java [] class Solution { public int prefixCount(String[] words, String pref) { int c = 0; int n = pref.length(); for (String w : words) { if (w.length() >= n && w.startsWith(pref)) { c++; } } return c; } } ``` ![download.jpeg](https://assets.leetcode.com/users/images/5e54ce8f-85c3-42eb-b14a-80d9b90e23c0_1736389445.0482821.jpeg)
45
7
['C++', 'Java', 'Python3']
7
counting-words-with-a-given-prefix
C++ || Easiest Solution || Substring
c-easiest-solution-substring-by-tarun_sa-my0u
\n// The easiest solution to this problem is:\n// Step 1: Calculate length of "pref"\n// Step 2: find substring of "words" from 0 to length of "pref"\n// if bot
tarun_sahnan
NORMAL
2022-02-27T04:02:00.556523+00:00
2022-02-27T04:02:00.556561+00:00
5,400
false
```\n// The easiest solution to this problem is:\n// Step 1: Calculate length of "pref"\n// Step 2: find substring of "words" from 0 to length of "pref"\n// if both match increment count by 1;\n\n\n\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n \n int count=0;\n int preflen=pref.size(); //step 1\n \n for(auto i:words){\n if(i.substr(0,preflen) == pref) //step 2\n count++; //if both matches then increment count by 1\n \n }\n return count; //return count\n \n }\n};\n```\nPlease Upvote, if you liked my solution.\nDont forget to visit my repo: https://github.com/tarunsahnan/LeetCode-Solutions
43
10
['C']
10
counting-words-with-a-given-prefix
[Java/Python 3] 1 liners and a follow-up.
javapython-3-1-liners-and-a-follow-up-by-zan0
\n\njava\n public int prefixCount(String[] words, String pref) {\n return (int)Stream.of(words).filter(w -> w.startsWith(pref)).count();\n }\n\npyt
rock
NORMAL
2022-02-27T04:01:55.662149+00:00
2022-06-20T17:50:05.982752+00:00
3,939
false
\n\n```java\n public int prefixCount(String[] words, String pref) {\n return (int)Stream.of(words).filter(w -> w.startsWith(pref)).count();\n }\n```\n```python\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(w.startswith(pref) for w in words)\n```\n\n----\n\n**Follow-up:**\n\n*Q*: A followup question from Google: what if the words are sorted lexicographically? -- credit to **@blackspinner**\n*A*: We can use binary search twice to locate the lower and upper bounds of the words that have the same prefix. Therefore, the time cost is O(klogn). e.g., \nAssume `perf = "abcd"`, we can search `"abcd"` and `"abce"` respectively.\n\n\n
35
2
[]
6
counting-words-with-a-given-prefix
[Python3, Java, C++] Find/IndexOf
python3-java-c-findindexof-by-tojuna-k03u
\n\n
tojuna
NORMAL
2022-02-27T04:01:58.335022+00:00
2022-02-27T04:16:07.002029+00:00
3,376
false
\n<iframe src="https://leetcode.com/playground/8dV5wFQP/shared" frameBorder="0" width="480" height="160"></iframe>\n
26
8
[]
9
counting-words-with-a-given-prefix
One-liner (count_if)
one-liner-count_if-by-votrubac-pud7
C++\ncpp\nint prefixCount(vector<string>& ws, string pref) {\n return count_if(begin(ws), end(ws), [&](const string &w){\n return w.compare(0, pref.siz
votrubac
NORMAL
2022-02-27T04:21:33.653453+00:00
2022-02-27T04:21:33.653484+00:00
2,154
false
**C++**\n```cpp\nint prefixCount(vector<string>& ws, string pref) {\n return count_if(begin(ws), end(ws), [&](const string &w){\n return w.compare(0, pref.size(), pref) == 0; \n });\n}\n```
25
10
['C']
5
counting-words-with-a-given-prefix
Java Solution | easy
java-solution-easy-by-amisha544-kv4w
\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int c = 0;\n for(String s : words) {\n if(s.indexOf(pref)==0) \n
amisha544
NORMAL
2022-02-27T05:55:52.722075+00:00
2022-02-27T06:22:39.822602+00:00
2,635
false
```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int c = 0;\n for(String s : words) {\n if(s.indexOf(pref)==0) \n c++;\n }\n return c; \n }\n}\n```
24
0
['Java']
8
counting-words-with-a-given-prefix
Python one line simple solution
python-one-line-simple-solution-by-tovam-7jsg
Python\n\n\ndef prefixCount(self, words: List[str], pref: str) -> int:\n\treturn sum([word.startswith(pref) for word in words])\n\n\nLike it ? please upvote !
TovAm
NORMAL
2022-03-01T11:29:14.051318+00:00
2022-03-01T11:29:14.051365+00:00
2,240
false
**Python**\n\n```\ndef prefixCount(self, words: List[str], pref: str) -> int:\n\treturn sum([word.startswith(pref) for word in words])\n```\n\n**Like it ? please upvote !**
19
0
['Python', 'Python3']
2
counting-words-with-a-given-prefix
1-liner vs Trie||C++ Py3 beats 100%
1-liner-vs-triec-beats-100-by-anwendeng-wnjs
IntuitionProvide 2 approaches 1 is 1-liner using starts_with other is using Trie. C++ & Python are done.Approach 1st C++ uses accumulate applying for words, wit
anwendeng
NORMAL
2025-01-09T00:12:52.745923+00:00
2025-01-09T07:32:13.053218+00:00
1,749
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Provide 2 approaches 1 is 1-liner using starts_with other is using Trie. C++ & Python are done. # Approach <!-- Describe your approach to solving the problem. --> 1. 1st C++ uses `accumulat`e applying for `words`, with a lambda defined by ``` [pref](int sum, auto& w){ return sum+=w.starts_with(pref); }); ``` 2. 2nd approach is using Trie. 3. The Trie solution has the similar process like 1st C++. Insert only `pref` in the Trie trie; define `start_with` function # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $O(|pref|+\sum_{w\in words}|w|)$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> 1-liner: $O(1)$ Trie: $O(|pref|)$ # Code || C++ , Python 1-liner 0ms beats 100% ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string& pref) { return accumulate(words.begin(), words.end(), 0, [pref](int sum, auto& w){ return sum+=w.starts_with(pref); }); } }; ``` ```Python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(w.startswith(pref) for w in words) ``` # Code using Trie||0ms beats 100% ``` // struct Trie for N alphabets const int N=26; struct Trie { Trie* next[N]; bool isEnd = 0; Trie() { fill(next, next+N, (Trie*)NULL); } ~Trie() { // cout<<"Destructor\n"; for (int i=0; i<N; ++i) { if (next[i] !=NULL) { delete next[i]; } } } void insert(string& word) { Trie* Node=this; for(char c: word){ int i=c-'a'; if(Node->next[i]==NULL) Node->next[i]=new Trie(); Node=Node->next[i]; } Node->isEnd=1; } }; class Solution { public: Trie trie; bool start_with(string& w){ Trie* Node=&trie; for( char c: w){ int i=c-'a'; if (Node->next[i]==NULL) return 0; Node=Node->next[i]; if (Node->isEnd) return 1; } return 0; } int prefixCount(vector<string>& words, string& pref) { trie.insert(pref); int cnt=0; for(string& w: words) cnt+=start_with(w); return cnt; } }; ``` # Trie is an advanced data structure. Using it one can solve many problems [[Leetcode 140. Word Break II](https://leetcode.com/problems/word-break-ii/solutions/5203799/dp-hash-vs-dp-trie-0ms-beats-100/) Please turn on English subtitles if necessary] [https://youtu.be/_E-fcmVmkYU?si=Ve6Z8zuPIi08k0VI](https://youtu.be/_E-fcmVmkYU?si=Ve6Z8zuPIi08k0VI)
18
4
['Trie', 'String Matching', 'C++', 'Python3']
5
counting-words-with-a-given-prefix
C++ | with explanation | easy
c-with-explanation-easy-by-aman282571-upjz
Explanation-\nCheck if word contains pref, and if it contains then it should be at 0th position\n\n\nclass Solution {\npublic:\n int prefixCount(vector<strin
aman282571
NORMAL
2022-02-27T04:01:20.154470+00:00
2022-02-27T04:01:20.154512+00:00
1,433
false
**Explanation-**\nCheck if word contains pref, and if it contains then it should be at ```0th``` position\n\n```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int ans=0;\n for(auto & word:words)\n if(word.find(pref)==0)\n ans++;\n return ans;\n }\n};\n```\nDo **UPVOTE** if it helps :)
15
6
['C']
2
counting-words-with-a-given-prefix
✅ Trie vs Brute-Force vs find()
trie-vs-brute-force-vs-find-by-xxvvpp-w9iw
Trie Method:\n\n1. First put all the words in the trie and keep on incrementing counting of prefix after every letter.\n2. Now traverse prefix and get the count
xxvvpp
NORMAL
2022-02-27T04:12:28.521853+00:00
2022-02-28T04:43:36.380313+00:00
1,489
false
**Trie Method**:\n\n1. First put all the words in the trie and keep on incrementing counting of prefix after every letter.\n2. Now traverse prefix and get the count , number of word this prefix has occured.\n\n**It is a Standard Trie Implementation ALgorithm**\n**C++**\n \n struct Node{\n Node* links[26];\n int prefix=0;\n \n bool contains(char c){\n return links[c-\'a\']!=0;\n } \n \n void create(char c,Node* node){\n links[c-\'a\']=node;\n }\n \n void increment(){\n prefix++;\n }\n \n int count(){\n return prefix;\n }\n \n Node* next(char c){\n return links[c-\'a\'];\n }\n };\n\t\n\t//Trie Class\n class Trie{\n Node* root; \n public:\n \n Trie(){\n root=new Node();\n }\n\t \n //insert words\n void insert(string word){\n Node* ptr=root;\n for(auto i:word){\n if(!ptr->contains(i)) ptr->create(i,new Node());\n ptr=ptr->next(i);\n ptr->increment();\n }\n }\n\t \n //return count of given prefix\n int cnt_pref(string word){\n Node* ptr=root;\n for(auto i:word){\n if(!ptr->contains(i)) return 0;\n ptr=ptr->next(i);\n }\n return ptr->count();\n }\n };\n\t\n\t//input class\n\tclass Solution {\n public:\n int prefixCount(vector<string>& words, string pref) {\n Trie trie;\n for(auto i:words) trie.insert(i); //no. of words*average length of strings\n int cnt= trie.cnt_pref(pref); //length of prefix\n return cnt;\n }\n };\n**Time** - O(number of words * average length of words + prefix_length)\n**Space** - O(Average length * 26)\n\n# Find() Algorithm Method:\n \n \n int prefixCount(vector<string>& words, string &pref) {\n int cnt=0;\n for(auto i:words){\n auto q= i.find(pref);\n if(q!=string::npos and q==0) cnt++;\n }\n return cnt;\n }\n**Time** - O(N * M)\n**Space** - O(1)\n\t\n# Brute Force\t\n\n bool check(string &x,string &y,int i){\n\t if(i==y.size()) return true;\n return x[i]==y[i]? check(x,y,i+1) : false;\n\t }\n\t \n int prefixCount(vector<string>& words, string &pref){\n int cnt=0;\n for(auto i:words){\n if(i.size()<pref.size()) continue;\n cnt+= check(i,pref,0)? 1 : 0 ;\n }\n return cnt;\n }\n**Time** - O(N * min(pref.size(),average length of strings)\n**Space** - O(1)\n
14
2
['C']
3
counting-words-with-a-given-prefix
🚀 0ms Solution! Beating 100% with Super Scott's Prefix Power and Trie! ⚡🔥
0ms-solution-beating-100-with-super-scot-dj1s
🦸 Super Scott's Coding Crusade! 🦸‍♂️"Listen up, hero! Prefixes are the first step in a word’s journey — just like the opening chapter of your life. Pay attentio
RSPRIMES1234
NORMAL
2025-01-09T01:57:55.036878+00:00
2025-01-09T02:39:00.231854+00:00
886
false
# 🦸 Super Scott's Coding Crusade! 🦸‍♂️ "Listen up, hero! Prefixes are the first step in a word’s journey — just like the opening chapter of your life. Pay attention, because every detail matters!" – Super Scott --- ![image.png](https://assets.leetcode.com/users/images/12a77db8-8aa8-481e-8fc4-b99c6275115c_1736387312.8344545.png) ## 🧐 **Understanding the Problem** Super Scott has a mission for you: You're given a list of words and a prefix. Your task is to count how many words in the list **start with that prefix**. Let’s break this heroic mission down step by step. --- ### **What is a Prefix?** A prefix is the starting portion of a word. Think of it like the opening scene of a blockbuster superhero movie. Here are some examples: - In the word `"attention"`, prefixes are: `"a"`, `"at"`, `"att"`, `"atte"`, and so on. - For the prefix `"at"`, the words `"attention"` and `"attend"` match, but `"pay"` does not. --- ### **Mission Objective** 1. **Inspect the Words**: For each word in the list, check if it starts with the given prefix. 2. **Count the Matches**: Keep track of how many words match the prefix. 3. **Return the Count**: At the end of the quest, report how many words were victorious. --- ### **Examples from Super Scott's Archive** #### Example 1: - **Input**: `words = ["pay", "attention", "practice", "attend"]` `pref = "at"` - **Output**: `2` - **Explanation**: The words `"attention"` and `"attend"` begin with `"at"`. #### Example 2: - **Input**: `words = ["leetcode", "win", "loops", "success"]` `pref = "code"` - **Output**: `0` - **Explanation**: No word starts with `"code"`. --- ### **Super Scott’s Wisdom** "Code like a hero, inspect every word, and honor the prefix — because in the world of programming, every detail counts!" – Super Scott --- ### **Solution 1** 💻 ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: l = len(pref) # Length of the prefix ans = 0 # Counter for words with the prefix for word in words: if len(word) >= l and word[:l] == pref: # Check if the word starts with the prefix ans += 1 return ans ``` ``` java [] class Solution { public int prefixCount(String[] words, String pref) { int ans = 0; int len = pref.length(); for (String word : words) { if (word.length() >= len && word.substring(0, len).equals(pref)) { ans++; } } return ans; } } ``` ``` cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int ans = 0; int len = pref.length(); for (string& word : words) { if (word.length() >= len && word.substr(0, len) == pref) { ans++; } } return ans; } }; ``` ``` javascript [] var prefixCount = function(words, pref) { let ans = 0; const len = pref.length; for (let word of words) { if (word.length >= len && word.slice(0, len) === pref) { ans++; } } return ans; }; ``` ``` csharp [] using System; public class Solution { public int PrefixCount(string[] words, string pref) { int ans = 0; int len = pref.Length; foreach (var word in words) { if (word.Length >= len && word.Substring(0, len) == pref) { ans++; } } return ans; } } ``` ``` ruby [] def prefix_count(words, pref) ans = 0 len = pref.length words.each do |word| if word.length >= len && word[0, len] == pref ans += 1 end end ans end ``` ``` go [] package main import "fmt" func prefixCount(words []string, pref string) int { ans := 0 l := len(pref) for _, word := range words { if len(word) >= l && word[:l] == pref { ans++ } } return ans } ``` ### **Explanation of the Code** 1. **Measure the Prefix**: First, calculate the length of the prefix (`l`) since we’ll compare only the first `l` characters of each word. 2. **Loop Through the Words**: For every word in the list: - Check if its length is at least as long as the prefix. - Compare the first `l` characters with the prefix. - If it matches, increment the count. 3. **Return the Count**: Once all words have been checked, return the final count. --- ### 🧑‍🏫 **Time Complexity Analysis:** #### **Time Complexity:** For each word in the list `words`, we compare the first `l` characters (where `l` is the length of the prefix `pref`) to check if it matches the prefix. This takes **O(l)** time for each word. Thus, if there are `n` words in `words`, the overall time complexity is **O(n * l)**, where `n` is the number of words and `l` is the length of the prefix. #### **Space Complexity:** The space complexity is **O(1)** because we are only using a few variables (`ans`, `l`), and the space used does not grow with the input size. ___ ___ # **Solution 2** 💻 ## Trie Data Structure for Prefix Count Solution We use a **Trie** (also known as a prefix tree) to efficiently handle the word counting problem based on prefixes. ### What is a Trie? A Trie is a tree-like data structure that stores strings in a way that allows for efficient querying of prefixes and exact matches. Each node in the Trie corresponds to a character in a word, and we can use it to store the number of words that share a certain prefix. ### Key Operations: 1. **Add Operation**: - For each word, we insert it character by character into the Trie. - We increment `startc` for every character of the word to indicate how many words share the same prefix. - We increment `endc` at the last character of the word to indicate that this is the end of a valid word. 2. **StartsWith Operation**: - To check how many words start with a given prefix, we return the `startc` value of the last character node of the prefix. ### Time Complexity: - **Add**: O(n), where n is the length of the word being inserted. - **StartsWith**: O(n), where n is the length of the prefix. ### Space Complexity: - O(m * n), where m is the number of unique characters and n is the total number of characters inserted. This accounts for the storage of each character in the Trie nodes. --- ### Code Implementation: ```python3 [] class Node: def __init__(self): self.dicto = {} self.startc = 0 class Trie: def __init__(self): self.head = Node() # Method to insert a word into the Trie def add(self, word): curr = self.head for char in word: if char not in curr.dicto: curr.dicto[char] = Node() curr = curr.dicto[char] curr.startc += 1 # Method to count how many words start with the given prefix def startsWith(self, prefix): curr = self.head for char in prefix: if char not in curr.dicto: return 0 curr = curr.dicto[char] return curr.startc class Solution: def prefixCount(self, words: List[str], pref: str) -> int: # Create a Trie and insert all words into it trie = Trie() for word in words: trie.add(word) # Use the Trie to find how many words start with the prefix return trie.startsWith(pref) ``` ``` java [] import java.util.HashMap; class TrieNode { HashMap<Character, TrieNode> dict = new HashMap<>(); int startCount = 0; } class Trie { TrieNode root; public Trie() { root = new TrieNode(); } public void add(String word) { TrieNode current = root; for (char c : word.toCharArray()) { current.dict.putIfAbsent(c, new TrieNode()); current = current.dict.get(c); current.startCount++; } } public int startsWith(String prefix) { TrieNode current = root; for (char c : prefix.toCharArray()) { if (!current.dict.containsKey(c)) { return 0; } current = current.dict.get(c); } return current.startCount; } } public class Solution { public int prefixCount(String[] words, String pref) { Trie trie = new Trie(); for (String word : words) { trie.add(word); } return trie.startsWith(pref); } } ``` ``` cpp [] #include <iostream> #include <unordered_map> #include <vector> #include <string> using namespace std; class TrieNode { public: unordered_map<char, TrieNode*> dict; int startCount = 0; }; class Trie { public: TrieNode* root; Trie() { root = new TrieNode(); } void add(string word) { TrieNode* current = root; for (char c : word) { if (current->dict.find(c) == current->dict.end()) { current->dict[c] = new TrieNode(); } current = current->dict[c]; current->startCount++; } } int startsWith(string prefix) { TrieNode* current = root; for (char c : prefix) { if (current->dict.find(c) == current->dict.end()) { return 0; } current = current->dict[c]; } return current->startCount; } }; class Solution { public: int prefixCount(vector<string>& words, string pref) { Trie trie; for (string word : words) { trie.add(word); } return trie.startsWith(pref); } }; ``` ``` csharp [] using System; using System.Collections.Generic; public class TrieNode { public Dictionary<char, TrieNode> Dict = new Dictionary<char, TrieNode>(); public int StartCount = 0; } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void Add(string word) { TrieNode current = root; foreach (char c in word) { if (!current.Dict.ContainsKey(c)) { current.Dict[c] = new TrieNode(); } current = current.Dict[c]; current.StartCount++; } } public int StartsWith(string prefix) { TrieNode current = root; foreach (char c in prefix) { if (!current.Dict.ContainsKey(c)) { return 0; } current = current.Dict[c]; } return current.StartCount; } } public class Solution { public int PrefixCount(string[] words, string pref) { Trie trie = new Trie(); foreach (string word in words) { trie.Add(word); } return trie.StartsWith(pref); } } ``` ``` go [] package main import "fmt" type TrieNode struct { dicto map[rune]*TrieNode startCount int } type Trie struct { root *TrieNode } func NewTrie() *Trie { return &Trie{root: &TrieNode{dicto: make(map[rune]*TrieNode)}} } func (t *Trie) Add(word string) { current := t.root for _, c := range word { if _, ok := current.dicto[c]; !ok { current.dicto[c] = &TrieNode{dicto: make(map[rune]*TrieNode)} } current = current.dicto[c] current.startCount++ } } func (t *Trie) StartsWith(prefix string) int { current := t.root for _, c := range prefix { if _, ok := current.dicto[c]; !ok { return 0 } current = current.dicto[c] } return current.startCount } func prefixCount(words []string, pref string) int { trie := NewTrie() for _, word := range words { trie.Add(word) } return trie.StartsWith(pref) } ``` ``` ruby [] class TrieNode attr_accessor :dict, :start_count def initialize @dict = {} @start_count = 0 end end class Trie def initialize @root = TrieNode.new end def add(word) curr = @root word.each_char do |char| curr.dict[char] ||= TrieNode.new curr = curr.dict[char] curr.start_count += 1 end end def starts_with(prefix) curr = @root prefix.each_char do |char| return 0 unless curr.dict[char] curr = curr.dict[char] end curr.start_count end end class Solution def prefix_count(words, pref) trie = Trie.new words.each { |word| trie.add(word) } trie.starts_with(pref) end end ``` ``` javascript [] class TrieNode { constructor() { this.dicto = {}; this.startCount = 0; } } class Trie { constructor() { this.root = new TrieNode(); } add(word) { let current = this.root; for (let char of word) { if (!current.dicto[char]) { current.dicto[char] = new TrieNode(); } current = current.dicto[char]; current.startCount++; } } startsWith(prefix) { let current = this.root; for (let char of prefix) { if (!current.dicto[char]) { return 0; } current = current.dicto[char]; } return current.startCount; } } function prefixCount(words, pref) { const trie = new Trie(); for (let word of words) { trie.add(word); } return trie.startsWith(pref); } ``` ### **Victory Awaits!** Go ahead, implement this and watch as your prefix-matching powers save the day! 💪✨ ![WhatsApp Image 2025-01-09 at 07.24.25_0d0e547b.jpg](https://assets.leetcode.com/users/images/9b431867-2c5b-4591-81ab-5aeb7ccb8201_1736387702.7284853.jpeg)
12
5
['Trie', 'C++', 'Java', 'Python3', 'Ruby', 'JavaScript', 'C#']
3
counting-words-with-a-given-prefix
🚀 100% Efficient Solution: Optimal Prefix Counter with Clarity & Speed! 🌟 || Approved ✅
100-efficient-solution-optimal-prefix-co-z1yp
IntuitionTo solve this problem, we need to count how many words in the given list start with the specified prefix. This can be efficiently done by iterating ove
venkat_pasapuleti
NORMAL
2025-01-09T02:51:55.526482+00:00
2025-01-09T03:19:42.324258+00:00
93
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> To solve this problem, we need to count how many words in the given list start with the specified prefix. This can be efficiently done by iterating over the list and checking if each word begins with the prefix. ![Screenshot 2025-01-09 081445.png](https://assets.leetcode.com/users/images/1a4d7daa-446a-4bbb-a732-f4c07518689c_1736391024.0580993.png) https://leetcode.com/u/Hari_Veera_Venkat/ # Approach <!-- Describe your approach to solving the problem. --> 1. **Iterate Through the List:** - Use a loop to iterate through each word in the input list `words`. 2. **Check Prefix:** - Skip the word if its length is less than the length of the prefix, as it cannot contain the prefix. - Use the `substr` function to extract the prefix-length substring of the current word and compare it to the given prefix. 3. **Increment Counter:** - If the word starts with the prefix, increment the result counter `res`. 4. **Return Result:** - After checking all words, return the value of `res`. # Complexity - **Time Complexity:** $$O(n \cdot k)$$ - \(n\): Number of words in the list. - \(k\): Length of the prefix. - For each word, we perform at most \(O(k)\) operations to extract and compare the prefix. - **Space Complexity:** $$O(1)$$ - No additional data structures are used apart from variables for counters. # Code ```c [] int prefixCount(char** words, int wordsSize, char* pref) { int count = 0; for (int i = 0; i < wordsSize; i++) { if (strncmp(words[i], pref, strlen(pref)) == 0) { count++; } } return count; } ``` ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int res = 0; for (int i = 0; i < words.size(); i++) { if (words[i].size() < pref.size()) continue; if (words[i].substr(0, pref.size()) == pref) res++; } return res; } }; ``` ```python [] class Solution(object): def prefixCount(self, words, pref): res=0; for word in words: if len(word) >= len(pref) and word[:len(pref)] == pref: res+=1; return res; ``` ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: res = 0 for word in words: if word.startswith(pref): res += 1 return res ``` ```java [] class Solution { public int prefixCount(String[] words, String pref) { int res = 0; for (String word : words) { if (word.length() >= pref.length() && word.substring(0, pref.length()).equals(pref)) { res++; } } return res; } } ``` # Key Points - **Efficient Filtering:** Skips unnecessary checks by comparing word lengths with the prefix upfront. - **Direct Comparison:** Uses `substr` to directly extract and compare prefixes, ensuring simplicity and clarity. - **Handles Edge Cases:** Works seamlessly for words shorter than the prefix or when no matches exist. - **Optimal for Large Inputs:** The solution is designed to handle large datasets efficiently. - **Clean & Readable Code:** Well-structured logic makes it easy to understand and maintain. 🌟 **Why You'll Love This Solution!** - **Clear & Simple 💡:** Designed for maximum readability. - **100% Efficiency Approved 🏆:** Handles large datasets effectively. - **Reusable 🎨:** Works with any list of words and prefix combinations. 💖 **Show Your Support!** 👍 If this solution helped you, hit that like button and drop your feedback below. Your encouragement motivates more optimized solutions! 🌍✨
10
0
['C', 'Python', 'C++', 'Java', 'Python3']
0
counting-words-with-a-given-prefix
💡 | O(n * m) | (C++, Java, Py3) -- 0ms Beats 100.00% | String Matching 🧠
on-m-c-java-py3-0ms-beats-10000-string-m-uebq
Intuition 🧩 The problem requires counting the number of words in an array that start with a given prefix. This can be efficiently solved using string matching
user4612MW
NORMAL
2025-01-09T00:46:06.793418+00:00
2025-01-09T08:56:36.155880+00:00
743
false
--- > ## Intuition 🧩 The problem requires counting the number of words in an array that start with a given prefix. This can be efficiently solved using string matching techniques. Specifically: - We check if each word starts with the prefix using the **find** function or slicing. --- > ## Approach 🎯 1. **Iterate through the array of words** For each word, check if it starts with the given prefix. 2. **Prefix Check** - In C++: Use $$std::string::find$$ with $$== 0$$ to check if the prefix matches the start of the word. - In Python: Use the $$startswith()$$ method. - In Java: Use the $$startsWith()$$ method. 3. **Count Matches** Increment the count whenever a match is found. --- > ## Complexity 📊 - **Time Complexity** $$O(n * m)$$ - **n** is the number of words in the array. - **m** is the average length of the words or the prefix. Each word is checked against the prefix, resulting in an overall complexity of $$O(n * m)$$. - **Space Complexity** **O(1)** The solution uses constant additional space. --- ## Code 💻 ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { return count_if(words.begin(), words.end(), [&](const string& word) { return word.find(pref) == 0; }); } }; ``` ```python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(word.startswith(pref) for word in words) ``` ```java [] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (String word : words) { if (word.startsWith(pref)) { count++; } } return count; } } ``` ```javascript [] var prefixCount = function(words, pref) { let count = 0; for (let word of words) { if (word.startsWith(pref)) { count++; } } return count; }; ``` > - **C++** > ![image.png](https://assets.leetcode.com/users/images/b2ee8f62-95db-468a-ba6e-8297cc995e90_1736383329.4776938.png) > - **Java** > ![image.png](https://assets.leetcode.com/users/images/c08b9956-5431-473d-9331-d883e2cdff5e_1736383339.8617845.png) > - **Python3** > ![image.png](https://assets.leetcode.com/users/images/ad70952c-83b7-4d5e-ac70-40f459925046_1736383350.2742326.png) ![Designer.png](https://assets.leetcode.com/users/images/5395952a-4267-4b87-b81f-f28780669704_1726803172.327018.png) --- ---
10
4
['String Matching', 'C++', 'Java', 'Python3', 'JavaScript']
5
counting-words-with-a-given-prefix
Swift💯 1liner+Swift6+Longhand
swift-1linerswift6longhand-by-upvotethis-9lvp
One-Liner, terse (accepted answer)One-Liner, Swift 6 (accepted answer)Good Interview Answers (accepted answers)
UpvoteThisPls
NORMAL
2025-01-09T00:16:37.188909+00:00
2025-01-09T00:16:37.188909+00:00
213
false
**One-Liner, terse (accepted answer)** ``` class Solution { func prefixCount(_ w: [String], _ p: String) -> Int { w.filter{$0.hasPrefix(p)}.count } } ``` **One-Liner, Swift 6 (accepted answer)** ``` class Solution { // Swift 6 required (leetcode still 5.x) func prefixCount(_ w: [String], _ p: String) -> Int { w.count{$0.hasPrefix(p)} } } ``` **Good Interview Answers (accepted answers)** ``` class Solution { func prefixCount(_ words: [String], _ pref: String) -> Int { var count = 0 for word in words { guard word.count >= pref.count, zip(word, pref).allSatisfy(==) else { continue } count += 1 } return count } } ``` ``` class Solution { func prefixCount(_ words: [String], _ pref: String) -> Int { var count = 0 for word in words where word.prefix(pref.count) == pref { count += 1 } return count } } ```
9
0
['Swift']
1
counting-words-with-a-given-prefix
✅Beats 100% | Simple and Easy Solution | C++| Java | Python | JavaScript
beats-100-simple-and-easy-solution-c-jav-bu1k
⬆️Upvote if it helps ⬆️Connect with me on Linkedin [Bijoy Sing]IntuitionThe problem requires us to count strings that start with a given prefix. The straightfor
BijoySingh7
NORMAL
2025-01-09T03:06:24.091018+00:00
2025-01-09T03:06:24.091018+00:00
2,741
false
# ⬆️Upvote if it helps ⬆️ --- ## Connect with me on Linkedin [Bijoy Sing] --- ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; int prefLen = pref.length(); for (string word : words) { if (word.length() >= prefLen) { if (word.substr(0, prefLen) == pref) { count++; } } } return count; } }; ``` ```python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: count = 0 prefLen = len(pref) for word in words: if len(word) >= prefLen: if word[:prefLen] == pref: count += 1 return count ``` ```java [] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; int prefLen = pref.length(); for (String word : words) { if (word.length() >= prefLen) { if (word.substring(0, prefLen).equals(pref)) { count++; } } } return count; } } ``` ```javascript [] var prefixCount = function(words, pref) { let count = 0; const prefLen = pref.length; for (let word of words) { if (word.length >= prefLen) { if (word.substring(0, prefLen) === pref) { count++; } } } return count; }; ``` # Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to count strings that start with a given prefix. The straightforward approach is to check each string in the array and verify if it starts with the prefix by comparing characters from the beginning. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize a counter to keep track of strings with the given prefix 2. For each word in the array: - First check if the word's length is at least equal to the prefix length - If yes, extract a substring from the word with the same length as prefix - Compare this substring with the prefix - If they match, increment the counter 3. Return the final count ![image.png](https://assets.leetcode.com/users/images/bed6fe42-7701-4803-a5ca-6828c2565888_1736391860.1091683.png) # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(N * K)$$ - N is the number of words in the input array - K is the length of the prefix - For each word, we need to check up to K characters to compare with prefix - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(1)$$ - We only use a constant amount of extra space - The counter variable is the only additional space needed - The substring comparisons don't require extra space that grows with input size ### *If you have any questions or need further clarification, feel free to drop a comment! 😊*
8
1
['Array', 'String', 'String Matching', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
7
counting-words-with-a-given-prefix
Beats 100% | String Matching | Solution for LeetCode#2185
beats-100-string-matching-solution-for-l-9t5d
IntuitionThe problem asks to count the number of strings in an array that start with a given prefix. The intuitive approach is to check each string in the array
samir023041
NORMAL
2025-01-09T00:06:24.759923+00:00
2025-01-09T01:07:59.715180+00:00
292
false
![image.png](https://assets.leetcode.com/users/images/c832a2d6-c45a-408c-a7a6-33899e66174b_1736381035.5194995.png) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem asks to count the number of strings in an array that start with a given prefix. The intuitive approach is to check each string in the array against the prefix. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate through each word in the words array. 2. For each word, use the startsWith() method to check if it begins with the given pref. 3. If a word starts with pref, increment a counter. 4. After checking all words, return the final count. # Complexity - Time complexity: O(n * m), where n is the number of words in the array and m is the average length of the words <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int n=words.length; int cnt=0; for(int i=0; i<n; i++){ if(words[i].startsWith(pref)){ cnt++; } } return cnt; } } ``` ```python [] class Solution(object): def prefixCount(self, words, pref): """ :type words: List[str] :type pref: str :rtype: int """ n=len(words) cnt=0 for i in range(n): if words[i].startswith(pref): cnt+=1 return cnt ``` ```cpp [] #include <vector> #include <string> class Solution { public: int prefixCount(const std::vector<std::string>& words, const std::string& pref) { int cnt = 0; for (const auto& word : words) { if (word.rfind(pref, 0) == 0) { // Checks if 'pref' is a prefix of 'word' cnt++; } } return cnt; } }; ``` ```swift [] class Solution { func prefixCount(_ words: [String], _ pref: String) -> Int { var count = 0 for word in words { if word.hasPrefix(pref) { count += 1 } } return count } } ```
8
5
['String', 'Swift', 'Python', 'C++', 'Java', 'Python3']
2
counting-words-with-a-given-prefix
python easy and straight forward approach
python-easy-and-straight-forward-approac-p1cu
\tclass Solution:\n\t\tdef prefixCount(self, words: List[str], pref: str) -> int:\n\t\t\tn = len(pref)\n\t\t\tcount = 0\n\t\t\tfor w in words:\n\t\t\t\tif w[:n]
shubham0925
NORMAL
2022-09-16T03:38:35.367860+00:00
2022-09-16T03:38:35.367893+00:00
972
false
\tclass Solution:\n\t\tdef prefixCount(self, words: List[str], pref: str) -> int:\n\t\t\tn = len(pref)\n\t\t\tcount = 0\n\t\t\tfor w in words:\n\t\t\t\tif w[:n] == pref:\n\t\t\t\t\tcount += 1\n\n\t\t\treturn count
8
0
['String', 'Python']
3
counting-words-with-a-given-prefix
Java One line Solution||Beats 💯✅✅
java-one-line-solutionbeats-by-jeril-joh-lsjl
IntuitionThe task is to count how many words in the array start with a specific prefix. The natural way to solve this is to iterate through each word and check
jeril-johnson
NORMAL
2025-01-09T05:06:50.428207+00:00
2025-01-09T05:12:33.439352+00:00
561
false
### **Intuition** The task is to count how many words in the array start with a specific prefix. The natural way to solve this is to iterate through each word and check if the prefix matches the beginning of the word. Java provides a built-in method, `String.startsWith`, which simplifies this process and ensures correctness. --- ### **Approach** 1. **Iterate through the list of words**: - Use a `for` loop to examine each word in the `words` array. 2. **Check if the word starts with the prefix**: - Use `word.startsWith(pref)` to determine if the word begins with the given prefix `pref`. 3. **Increment the count**: - If the word matches, increase the count by 1. 4. **Return the count**: - After processing all the words, return the final count. --- ### **Complexity** - **Time Complexity**: - $$O(n \cdot m)$$, where \(n\) is the number of words in the array, and \(m\) is the length of the prefix. - We iterate through each word (\(O(n)\)). - For each word, we check if it starts with the prefix (\(O(m)\)). - **Space Complexity**: - $$O(1)$$. - No additional space is used; we only maintain a counter. --- ### **Edge Cases** 1. **Empty prefix** (`pref = ""`): - Every word matches an empty prefix, so the count equals the number of words in the array. 2. **Empty array** (`words = []`): - The result is `0` since there are no words to check. 3. **No matches**: - If no word starts with the prefix, the result is `0`. --- ### **Code** ```java class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (String word : words) { if (word.startsWith(pref)) { count++; } } return count; } } ``` --- ### **Example Walkthrough** #### Input: ```text words = ["apple", "apricot", "banana", "apex"] pref = "ap" ``` #### Execution: 1. Check `"apple"`: Starts with `"ap"`. Count = 1. 2. Check `"apricot"`: Starts with `"ap"`. Count = 2. 3. Check `"banana"`: Does not start with `"ap"`. Count = 2. 4. Check `"apex"`: Starts with `"ap"`. Count = 3. #### Output: ```text 3 ``` ![image.png](https://assets.leetcode.com/users/images/52597733-42e6-4220-9ff9-f6475fd13da8_1736399546.3465905.png)
7
0
['Java']
0
counting-words-with-a-given-prefix
0ms | Beats 100.00% | Using Trie | Efficient, Easy & Simple C++ Solution | Full Explained
0ms-beats-10000-using-trie-efficient-eas-5s6a
Advantages of Using Trie Fast prefix checks, especially for multiple queries or overlapping prefixes. Efficient memory usage for storing common prefixes across
HarshitSinha
NORMAL
2025-01-09T04:13:20.665334+00:00
2025-01-09T04:13:20.665334+00:00
714
false
# Advantages of Using Trie - Fast prefix checks, especially for multiple queries or overlapping prefixes. - Efficient memory usage for storing common prefixes across words. # Intuition The solution leverages the Trie data structure to efficiently handle prefix-based operations. Tries are particularly useful when we need to perform repeated prefix queries, as they allow searching in 𝑂(𝑝) time, where 𝑝 is the length of the prefix. Here: - Insertion of the prefix into the Trie ensures that we have a quick way to validate prefixes. - The `start_with` function traverses the Trie to check if any word starts with the given prefix. <!-- Describe your first thoughts on how to solve this problem. --> # Approach 1. Trie Construction: - A `Trie` node is implemented with `next `pointers for the 26 lowercase English letters and a boolean `isEnd` to mark the end of a word. - The `insert` function adds the prefix pref to the Trie. 2. Prefix Validation: - The `start_with `function checks if the current word starts with the inserted prefix by traversing the Trie. - The traversal stops as soon as we detect the prefix (`isEnd` is true), reducing unnecessary checks. 3. Counting Matches: - Iterate through all words in `words` and count those that start with the given prefix using the `start_with` function. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(p+n⋅w) Since` 𝑝≪𝑛` in most scenarios, the overall complexity can be approximated to **𝑂(𝑛⋅𝑤)**, which aligns with linear traversal of all words. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(p⋅N)≈O(p) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] const int N=26; struct Trie { Trie* next[N]; bool isEnd = 0; Trie() { fill(next, next+N, (Trie*)NULL); } ~Trie() { for (int i=0; i<N; ++i) { if (next[i] !=NULL) { delete next[i]; } } } void insert(string& word) { Trie* Node=this; for(char c: word){ int i=c-'a'; if(Node->next[i]==NULL) Node->next[i]=new Trie(); Node=Node->next[i]; } Node->isEnd=1; } }; class Solution { public: Trie trie; bool start_with(string& w){ Trie* Node=&trie; for( char c: w){ int i=c-'a'; if (Node->next[i]==NULL) return 0; Node=Node->next[i]; if (Node->isEnd) return 1; } return 0; } int prefixCount(vector<string>& words, string& pref) { trie.insert(pref); int cnt=0; for(string& w: words) cnt+=start_with(w); return cnt; } }; ```
7
0
['Array', 'Two Pointers', 'String', 'Dynamic Programming', 'Trie', 'Recursion', 'Suffix Array', 'String Matching', 'Prefix Sum', 'C++']
2
counting-words-with-a-given-prefix
[JavaScript] Easy to understand - 1 line
javascript-easy-to-understand-1-line-by-e6njj
The core strategy for this problem is straightforward:\n- traverse the list\n- check each word is with a given prefix\n\nI guess there won\'t be any problem wit
poppinlp
NORMAL
2022-03-02T23:45:23.089851+00:00
2022-03-02T23:46:24.447560+00:00
801
false
The core strategy for this problem is straightforward:\n- traverse the list\n- check each word is with a given prefix\n\nI guess there won\'t be any problem with how to do the traversal. So, the only problem is how to check the prefix?\n\nWe could use `RegExp`, `indexOf`, `startsWith`, or even `slice` the first part.\nJust choose anyone you like, here are 2 samples from me:\n\n## Sample 1\n\n```js\nconst prefixCount = (words, pref) => {\n let count = 0;\n for (const word of words) {\n word.startsWith(pref) && ++count;\n }\n return count;\n}\n```\n\n## Sample 2\n\n```js\nconst prefixCount = (words, pref) => words.filter(word => word.startsWith(pref)).length;\n```
7
1
['JavaScript']
2
counting-words-with-a-given-prefix
[JavaScript] 1 line solution
javascript-1-line-solution-by-tgldr-js6j
\nvar prefixCount = function(words, pref) {\n return words.filter(word => word.slice(0, pref.length) === pref).length;\n};\n
tgldr
NORMAL
2022-02-27T04:08:52.187702+00:00
2022-02-27T04:09:06.182711+00:00
472
false
```\nvar prefixCount = function(words, pref) {\n return words.filter(word => word.slice(0, pref.length) === pref).length;\n};\n```
7
1
['JavaScript']
3
counting-words-with-a-given-prefix
Counting Words With a Given Prefix - Optimized [C++]
counting-words-with-a-given-prefix-optim-q8qb
IntuitionThe problem involves checking whether each word in the list starts with a specific prefix. The task can be efficiently tackled by leveraging string com
moveeeax
NORMAL
2025-01-09T13:35:33.764127+00:00
2025-01-09T13:35:33.764127+00:00
28
false
# Intuition The problem involves checking whether each word in the list starts with a specific prefix. The task can be efficiently tackled by leveraging string comparison methods. # Approach 1. Iterate through each word in the `words` array. 2. For each word: - Check if its size is greater than or equal to the prefix size. - Compare the substring of the word (up to the prefix length) with the prefix. 3. Increment a counter for each match. 4. Return the counter. This approach ensures we only compare valid substrings and avoids unnecessary computations for words shorter than the prefix. # Complexity - **Time complexity**: - Iterating through all words takes \(O(n)\), where \(n\) is the number of words. - Comparing the prefix with a substring takes \(O(m)\), where \(m\) is the length of the prefix. - Overall complexity: \(O(n \cdot m)\). - **Space complexity**: - The algorithm uses a constant amount of extra space, hence \(O(1)\). # Code with Comments ```cpp class Solution { public: int prefixCount(vector<string>& words, string pref) { short res = 0; // Counter to store the number of matches for (auto &w : words) { // Check if the word is at least as long as the prefix if (w.size() >= pref.size() && w.compare(0, pref.size(), pref) == 0) { res++; // Increment counter if prefix matches } } return res; // Return the total count of matching words } }; ```
6
0
['C++']
1
counting-words-with-a-given-prefix
Simple | Python 1 Liner | C++ 3 Liner | Beats 100%
very-simple-python-1-liner-c-3-liner-bea-fecj
Beats 100%IntuitionTo solve this problem, we want to count how many strings in the given list of words start with a specific prefix. The solution can utilize th
joshuajinu
NORMAL
2025-01-09T06:21:48.833155+00:00
2025-01-09T15:51:07.530725+00:00
174
false
# Beats 100% # Intuition To solve this problem, we want to count how many strings in the given list of words start with a specific prefix. The solution can utilize the startswith functionality or compare substrings directly for optimal performance. The task is straightforward because comparing substrings or prefixes can be done efficiently. # Approach - Iterate over the list of words. - - Maintain a counter to keep track of words that satisfy the condition. - For each word, check if it starts with the given prefix using substring, if yes, increment the counter. - Return the final count. # Complexity ### Time complexity: 𝑂(𝑛⋅𝑚) - O(n⋅m), where: - 𝑛 : n is the number of words in the list. - 𝑚 : m is the length of the prefix. ### Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) : as we do not use any extra space that grows with input size. ### If you found this explanation helpful, an upvote would be greatly appreciated! # Code ```python [] class Solution(object): def prefixCount(self, words, pref): return (sum(wrd[0:len(pref)]==pref for wrd in words)) ``` ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int cnt=0, l=pref.size(); for(string word: words){ cnt += word.substr(0, l)==pref;} return cnt; } }; ```
6
0
['String', 'String Matching', 'Python']
0
counting-words-with-a-given-prefix
Beats 100%✅✅|| Simple O(NM)
beats-100-simple-onm-by-arunk_leetcode-qz9e
IntuitionWe iterate through each word in the given list and check if the word starts with the given prefix.Approach Initialize a counter cnt to 0. Iterate throu
arunk_leetcode
NORMAL
2025-01-09T05:42:35.447596+00:00
2025-01-09T05:42:35.447596+00:00
628
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> We iterate through each word in the given list and check if the word starts with the given prefix. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize a counter `cnt` to 0. 2. Iterate through each word in the list. 3. Use two pointers, one for the word and another for the prefix. 4. Compare characters one by one until the prefix is fully matched or characters mismatch. 5. If the prefix is matched, increment the counter. 6. Return the counter. # Complexity - Time complexity: $$O(n \cdot m)$$, where \(n\) is the number of words and \(m\) is the average length of the words or the prefix. - Space complexity: $$O(1)$$, as we are using constant extra space. # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int cnt = 0; for (auto it : words) { int i = 0, j = 0; while (i < it.size() && j < pref.size()) { if (it[i] == pref[j]) { i++; j++; } else break; } if (j == pref.size()) cnt++; } return cnt; } }; ``` ```Java [] class Solution { public int prefixCount(String[] words, String pref) { int cnt = 0; for (String word : words) { int i = 0, j = 0; while (i < word.length() && j < pref.length()) { if (word.charAt(i) == pref.charAt(j)) { i++; j++; } else break; } if (j == pref.length()) cnt++; } return cnt; } } ``` ```Python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: cnt = 0 for word in words: i, j = 0, 0 while i < len(word) and j < len(pref): if word[i] == pref[j]: i += 1 j += 1 else: break if j == len(pref): cnt += 1 return cnt ```
6
0
['Array', 'String', 'Python', 'C++', 'Java']
3
counting-words-with-a-given-prefix
C++ Easy Solution using only One For loop and One If Condition
c-easy-solution-using-only-one-for-loop-agp8n
IntuitionThe intuition is to iterate through each word in the words array, extract its prefix of the same length as pref, and count how many of these prefixes m
_sxrthakk
NORMAL
2024-06-29T12:27:33.806351+00:00
2025-01-09T03:34:42.550952+00:00
235
false
# Intuition The intuition is to iterate through each word in the words array, extract its prefix of the same length as pref, and count how many of these prefixes match pref. # Approach **Initialization :** Start with a counter c initialized to zero. **Iterate through Words :** Loop through each word in the words array. **Check Prefix :** - For each word, extract the substring from the beginning with the same length as pref. - Compare this substring with pref. - If they match, increment the counter c. **Return Result :** - After checking all words, c will contain the number of strings that have pref as a prefix. - Return c as the final result. # Code ``` class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; int n=pref.size(); for(int i=0;i<words.size();i++){ string a=words[i].substr(0,n); if(a==pref) c++; } return c; } }; ```
6
0
['String', 'String Matching', 'C++']
0
counting-words-with-a-given-prefix
Easiest Substring Method In C++ || 100% || 2 line logic
easiest-substring-method-in-c-100-2-line-epxj
IntuitionThe task requires counting the words that start with a given prefix. We can solve this efficiently by iterating through the words and checking if the p
Sajaljha
NORMAL
2025-01-09T17:21:18.470879+00:00
2025-01-09T17:21:18.470879+00:00
31
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The task requires counting the words that start with a given prefix. We can solve this efficiently by iterating through the words and checking if the prefix matches the start of each word. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize a counter to keep track of the matches. 2. Loop through each word in the list `words`. 3. Extract a substring from the start of the word, with a length equal to the prefix. 4. Compare this substring with the given prefix: - If they are equal, increment the counter. 5. After the loop, return the counter as the final result. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(n \cdot m)$$, where $$n$$ is the number of words and $$m$$ is the length of the prefix. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(1)$$, since no additional data structures are used. # Code ```cpp class Solution { public: int prefixCount(vector<string>& words, string pref) { ios::sync_with_stdio(false); cin.tie(NULL); int cnt = 0; for (const string& word : words) { if (word.substr(0, pref.size()) == pref) { cnt++; } } return cnt; } };
5
0
['C++']
0
counting-words-with-a-given-prefix
🔥Easy Lightning-Fast Prefix Counter: Beats 100% in Runtime! 🚀
easy-lightning-fast-prefix-counter-beats-4s07
IntuitionThe goal is to count the number of strings in the given list of words that start with the specified prefix. Since prefixes are always located at the be
Kushagra_Singh_1100
NORMAL
2025-01-09T10:59:03.817792+00:00
2025-01-09T10:59:03.817792+00:00
94
false
# Intuition The goal is to count the number of strings in the given list of words that start with the specified prefix. Since prefixes are always located at the beginning of the string, we can iterate over the words and compare their first characters with the prefix until we find a mismatch or confirm the prefix matches. # Approach 1.Initialize Count: Start with a counter count initialized to 0 to keep track of the number of words that match the prefix. 2.Iterate Through Words: Loop through each word in the given list of words. 3.Compare Prefix: For each word, compare its first len characters (where len is the length of the prefix) with the prefix. 4.Use a nested loop to compare character by character. If a mismatch is found, break out of the inner loop and skip to the next word. 5.Increment Count: If no mismatch is found, increment the count as the word starts with the given prefix. Return Count: Finally, return the total count after all words have been checked. This approach ensures that we carefully evaluate each word for the prefix match while maintaining simplicity in implementation. # Complexity - Time complexity: The time complexity is O(n * m), where n is the number of words in the list, and m is the length of the prefix. This is because we compare up to m characters for each of the n words. - Space complexity: The space complexity is O(1) as we are not using any additional data structures and only keeping track of a few variables. # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; int len = pref.length(); for(string word: words){ bool flag = false; for(int i =0; i<len; i++){ if(word[i]!=pref[i]){ flag = true; break; } } if(flag==false){ count++; } } return count; } }; ```
5
0
['C++']
2
counting-words-with-a-given-prefix
Eassyyy Pessyyy Solution🔥| Runtime 100% 🔥| Easy to understand ✅
eassyyy-pessyyy-solution-runtime-100-eas-9dmc
IntuitionThe problem is about counting the number of words in the given list words that start with a specific prefix pref. A prefix is a substring at the beginn
jaitaneja333
NORMAL
2025-01-09T04:19:51.156375+00:00
2025-01-09T04:21:04.372634+00:00
229
false
![Screenshot 2025-01-09 093958.png](https://assets.leetcode.com/users/images/734c5794-bf41-4d21-a1d4-668ef448e9e8_1736396216.180397.png) # Intuition The problem is about counting the number of words in the given list words that start with a specific prefix pref. A prefix is a substring at the beginning of a string. For each word, we check if its starting characters match the given prefix. This requires an exact character-by-character match for the length of the prefix. # Approach 1. Initialize a counter count to zero to keep track of the number of words starting with the prefix. 2. Iterate through each word in the input vector words: * Extract a substring from the beginning of the word with a length equal to the length of the prefix using substr(). * Compare this substring with pref. * If they are equal, increment the counter count. 3. After iterating through all the words, return the value of count. # Complexity ### Time Complexity: `O(n.m)` * Let n be the number of words in the input list words and m be the average length of a word. * The substr() operation takes O(k), where k is the length of the prefix pref. * Comparing two strings of length m takes O(m). * For each word, the operations take O(m), and since there are n words, the total time complexity is O(n⋅m). ### Space Complexity: `O(1)` * The algorithm uses constant extra space O(1) since no additional data structures are used (besides the counter and temporary substrings). # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; for(int i = 0; i < words.size(); i++ ){ if(words[i].substr(0,pref.size()) == pref){ count++; } } return count; } }; ``` ```Java [Java] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (String word : words) { if (word.startsWith(pref)) { count++; } } return count; } } ``` ![Shinchan_upvote.jpg](https://assets.leetcode.com/users/images/de091c5e-0765-4809-93ce-0addcc8024dc_1736396253.9402227.jpeg)
5
0
['Array', 'String', 'String Matching', 'C++', 'Java']
3
counting-words-with-a-given-prefix
🔥Beats 💯|| 2 methods 🎯|| C++ || Find || Substring || Easy 🚀✅
beats-2-methods-c-find-substring-easy-by-ozt8
Intuition📚We check all strings in vector and if prefix of that string match pref string given -> increment count for the result.Approach🛠️Version 1: Find in a s
Phuc_code_ga
NORMAL
2025-01-09T03:34:08.303537+00:00
2025-01-09T03:34:08.303537+00:00
100
false
# Intuition📚 We check all strings in vector and if prefix of that string match pref string given -> increment count for the result. --- # Approach🛠️ # Version 1: Find in a string A loop for checking all strings in the array and use find function of std::string. ``` size_t find(const std::string& str) //it will return the first position of the first substring found in the current string. ``` So that if find return 0, it means that the pref string is the preffix of words[i], then incrementing cnt. # Complexity🚀 - Time complexity: O(n.m) ⏱️ n is for the loop, m is for find function - Space complexity: O(1) 🗂️ ![image.png](https://assets.leetcode.com/users/images/4870b025-8589-4b9c-be10-25033e3b6272_1736393443.3972106.png) # version 2: Substring matching A loop for checking all strings in the array and use find function of std::string. ``` std::string substr(size_t pos = 0, size_t len = npos) const //return the substring that start from pos, with length 'len' ``` So that if we check substring of words[i], which start from index 0 and having `pref.size()`, if that substring match pref string, then incrementing cnt. # Complexity🚀 - Time complexity: O(n.p) ⏱️ n is for the loop, and p is for extracting a substring of size p. - Space complexity: O(p) 🗂️ The `substr` function create a temporary substring of size p for each word in the vector. ![image.png](https://assets.leetcode.com/users/images/43ce7899-ced9-49b3-b976-38a5d2a1ee82_1736393478.6542516.png) # Version 1 ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int cnt = 0; for(int i = 0; i < words.size(); i++){ if(words[i].find(pref) == 0){ cnt++; } } return cnt; } }; ``` # Version 2 ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int cnt = 0; for(int i = 0; i < words.size(); i++){ if(words[i].substr(0, pref.size()) == pref){ cnt++; } } return cnt; } }; ``` ![image.png](https://assets.leetcode.com/users/images/d1172eac-d39a-49bf-9591-0705444807a2_1736393523.377854.png)
5
0
['String', 'String Matching', 'C++']
2
counting-words-with-a-given-prefix
Simple Solution | Beats 100%
simple-solution-beats-100-by-shreyas_kum-fvto
Code
Shreyas_kumar_m
NORMAL
2025-01-09T00:41:43.087299+00:00
2025-01-09T00:41:43.087299+00:00
205
false
# Code ```javascript [] /** * @param {string[]} words * @param {string} pref * @return {number} */ var prefixCount = function(words, pref) { let count = 0; for(let i=0;i<words.length;i++){ if(words[i].startsWith(pref)){ count++; } } return count; }; ```
5
0
['JavaScript']
0
counting-words-with-a-given-prefix
C++ || Easy Solution
c-easy-solution-by-vineet_raosahab-2z1n
\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int cnt=0;\n int n=pref.size();\n for(auto s:words
VineetKumar2023
NORMAL
2022-02-27T04:06:18.971820+00:00
2022-02-27T04:06:18.971847+00:00
316
false
```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int cnt=0;\n int n=pref.size();\n for(auto s:words)\n {\n if(s.size()>=pref.size())\n {\n if(s.substr(0,n)==pref)\n cnt++;\n }\n }\n return cnt;\n }\n};\n```
5
2
[]
0
counting-words-with-a-given-prefix
Java Code| Easy Solution |
java-code-easy-solution-by-patilprajakta-0esl
Code
patilprajakta
NORMAL
2025-01-09T14:36:18.239431+00:00
2025-01-09T14:36:18.239431+00:00
23
false
# Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (int i = 0; i < words.length; i++) { if (words[i].startsWith(pref)) count++; } return count; } } ```
4
0
['Java']
0
counting-words-with-a-given-prefix
Beginner Approach || Brute Force || Easy C++ Code
beginner-approach-brute-force-easy-c-cod-or9a
IntuitionThe function iterates through each string in the words vector and checks if it starts with the given prefix pref.Approach Iterate through each word: Lo
shweta_2004
NORMAL
2025-01-09T09:03:24.486749+00:00
2025-01-09T09:03:24.486749+00:00
102
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The function iterates through each string in the words vector and checks if it starts with the given prefix pref. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate through each word: Loop through each string in the words vector. 2. Check for prefix: For each word, use find(pref) to determine if the word starts with the prefix pref. This is done by checking if find(pref) == 0, which means the prefix is found at the beginning of the word. 3. Count matches: Every time a word matches the prefix, increment the counter. 4. Return the count: After processing all the words, return the total count of words that start with the given prefix. # Complexity - Time complexity: $$O(N * M)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int n = words.size(); int count =0; for(int i=0;i<n;i++) { if(words[i].find(pref)==0) count++; } return count; } }; ```
4
0
['Array', 'String', 'String Matching', 'C++']
0
counting-words-with-a-given-prefix
Best Solution for Arrays, Prefix Sum 🚀 in C++, Python and Java || 100% working
best-solution-for-arrays-prefix-sum-in-c-w49h
Intuition💡 The problem asks to count how many words in the list start with the given prefix. We can use string slicing or substring comparison to check each wor
BladeRunner150
NORMAL
2025-01-09T07:57:22.768644+00:00
2025-01-09T07:57:22.768644+00:00
94
false
# Intuition 💡 The problem asks to count how many words in the list start with the given prefix. We can use string slicing or substring comparison to check each word’s prefix. # Approach 1️⃣ For each word in the list, compare its prefix with the given prefix. 2️⃣ Slice the word up to the length of the prefix and check if they match. 3️⃣ If they match, increase the counter. # Complexity - **Time complexity:** $$O(n \times m)$$, where `n` is the number of words and `m` is the length of the prefix. - **Space complexity:** $$O(1)$$, as we only need a few extra variables for the count. # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int n = pref.size(); int ans = 0; for (string& word : words) { if (word.substr(0, n) == pref) { ans++; } } return ans; } }; ``` ```python [] class Solution(object): def prefixCount(self, words, pref): n = len(pref) ans = 0 for i in words: if i[:n] == pref: ans += 1 return ans ``` ```java [] class Solution { public int prefixCount(String[] words, String pref) { int n = pref.length(); int ans = 0; for (String word : words) { if (word.startsWith(pref)) { ans++; } } return ans; } } ``` 🚀 **Counting prefixes across languages!** 😎 <img src="https://assets.leetcode.com/users/images/7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg" alt="upvote" width="150px"> # Connect with me on LinkedIn for more insights! 🌟 Link in bio
4
0
['Array', 'String', 'String Matching', 'Python', 'C++', 'Java', 'Python3']
1
counting-words-with-a-given-prefix
✅100% || C++ || Python || String Matching Algorithms ||🔥Efficient Prefix Count Solutions || Easy
100-c-python-string-matching-algorithms-hetjk
IntuitionThe goal is to determine how many strings in the words list start with the given prefix pref. This can be efficiently done by checking the prefix of ea
Rohithaaishu16
NORMAL
2025-01-09T06:42:58.614825+00:00
2025-01-09T06:42:58.614825+00:00
34
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The goal is to determine how many strings in the words list start with the given prefix pref. This can be efficiently done by checking the prefix of each string in the list. # Approach <!-- Describe your approach to solving the problem. --> We can iterate through the words list and check if each word starts with the prefix pref using different methods. If a word starts with the prefix, we increment our count. We can achieve this using several approaches: 1. Using the startswith method and slicing to compare substrings in Python 2. Using various C++ methods (substr(), find(), mismatch(), equal(), compare()). # Complexity - Time complexity: All solutions have a time complexity of $$O(n)$$, where $$n$$ is the number of strings in the words list, since we need to check each word. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: All solutions have a space complexity of $$O(1)$$, since we only use a few extra variables to store the count and do not use additional data structures. <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code - C++ - using substr() ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0,p=pref.size(); for(string w:words){ if(w.substr(0,p)==pref) c++; } return c; } }; ``` - using find() ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; for(string w:words){ if (w.find(pref)==0) c++; } return c; } }; ``` - using mismatch() ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; for(string w:words){ if(mismatch(pref.begin(), pref.end(), w.begin()).first == pref.end()) c++; } return c; } }; ``` - using equal() ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; for(string w:words){ if (w.size() >= pref.size() && equal(pref.begin(), pref.end(), w.begin())) c++; } return c; } }; ``` - using compare() ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; for(string w:words){ if (w.compare(0, pref.size(), pref) == 0) c++; } return c; } }; ``` # Code - Python - using startswith() ```python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: return sum(w.startswith(pref) for w in words) ``` - using slicing ```python [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: c = 0 for w in words: if w[:len(pref)] == pref: c += 1 return c ```
4
0
['Array', 'String', 'String Matching', 'C++', 'Python3']
0
counting-words-with-a-given-prefix
✅✅ Very easy solution beat 100% time complexity🔥🔥
very-easy-solution-beat-100-time-complex-xwkz
Intuition: The problem revolves around identifying words in a list (words) that start with a given prefix (pref). The simplest method is to directly compare the
ishanbagra
NORMAL
2025-01-09T04:20:36.045516+00:00
2025-01-09T04:20:36.045516+00:00
95
false
Intuition: The problem revolves around identifying words in a list (words) that start with a given prefix (pref). The simplest method is to directly compare the starting segment of each word with pref. Since the prefix length is fixed and known, the task reduces to extracting the first len characters of each word and checking for equality. Using substr allows us to neatly extract the prefix of each word for comparison. If they match, we increment a counter. Approach: First, determine the length of the prefix pref using pref.size(). Initialize a counter variable (count) to zero. Iterate through the list of words (words): For each word, extract its prefix of length len using substr(0, len). Compare this extracted prefix with pref. If they are equal, increment the counter. After completing the loop, return the value of the counter as the result. Complexity: Time Complexity: The substr function runs in O(m), where 𝑚 is the length of the prefix. Iterating through all n words in the list results in a time complexity of O(n).Combining these, the overall time complexity is O(n⋅m), where:𝑛 n = number of words. 𝑚 m = length of the prefix. Space Complexity: No additional data structures are used aside from the counter and the loop variable. The function operates in O(1) auxiliary space. ![Screenshot 2025-01-09 094525.png](https://assets.leetcode.com/users/images/02ac5ae0-183b-4a62-9834-3826ec8d12f5_1736396298.2145996.png) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count=0; int len=pref.size(); for(int i=0;i<words.size();i++) { if(words[i].substr(0,len)==pref) { count++; } } return count; } }; ``` ![Screenshot 2024-11-06 113013.png](https://assets.leetcode.com/users/images/96732648-b871-44b7-824a-3ea8b7083981_1736396344.1814322.png)
4
0
['String', 'C++']
2
counting-words-with-a-given-prefix
Solution in C
solution-in-c-by-vickyy234-se80
Code
vickyy234
NORMAL
2025-01-09T03:21:04.234298+00:00
2025-01-09T04:52:30.878835+00:00
156
false
# Code ```c [] int prefixCount(char** words, int wordsSize, char* pref) { int len = strlen(pref), count = 0; for (int i = 0; i < wordsSize; i++) { if (strncmp(words[i], pref, len) == 0) count++; } return count; } ```
4
0
['C']
0
counting-words-with-a-given-prefix
ads;
ads-by-abhaydeep_24-2ph7
Complexity Time complexity: O(N*M) N= no.ele in words array M=length of pref string Space complexity: O(1) Code
abhaydeep_24
NORMAL
2025-01-09T01:13:02.008773+00:00
2025-01-09T01:13:02.008773+00:00
73
false
# Complexity - Time complexity: O(N*M) N= no.ele in words array M=length of pref string <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int n=words.size(); int count=0; for(int i=0;i<n;i++){ string word=words[i]; if(word.find(pref)==0) count++; } return count; } }; ```
4
0
['C++']
0
counting-words-with-a-given-prefix
Naive best Approach
naive-best-approach-by-luffy240605-8d2a
ApproachTraversing through whole array words and checking if pref == curr_pref if yes the incrementing the counter else continue. Also : if length of word is sm
luffy240605
NORMAL
2025-01-09T01:08:14.314974+00:00
2025-01-09T01:08:14.314974+00:00
162
false
# Approach Traversing through whole array words and checking if pref == curr_pref if yes the incrementing the counter else continue. Also : if length of word is smaller than pref then continue <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O( n * length of prefix ) ~ O(n^2) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int cnt = 0; for (auto x : words) { if (x.length() < pref.length()) continue; string curr_pref = ""; for (int j = 0; j < pref.length(); j++) { curr_pref += x[j]; } if (curr_pref == pref) cnt++; // else // continue } return cnt; } }; ```
4
0
['C++']
0
counting-words-with-a-given-prefix
Exactly did what was asked to check if prefix is same & did some optimization before check||Runs 0ms
exactly-did-what-was-asked-to-check-if-p-2vu5
Approach Little Optimization: First just little check before checking the whole prefix presence if their first character same and length should be >= pref Compl
Harsh-X
NORMAL
2025-01-09T00:38:48.592291+00:00
2025-01-09T00:38:48.592291+00:00
77
false
![image.png](https://assets.leetcode.com/users/images/9e8a635d-6d9d-4f98-bd95-f686123ff393_1736382891.6574821.png) # Approach <!-- Describe your approach to solving the problem. --> - Little Optimization: First just little check before checking the whole prefix presence if their first character same and length should be >= pref # Complexity - Time complexity: **O(N*M)** -> N = words.length(), M = Prefix.length() <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: **O(1)** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] #pragma GCC optimize("O3,unroll-loops,Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx") static const auto harsh = []() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }(); class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; for(int i = 0; i<words.size(); i++){ // Little Optimization: First just little check if their first character same and length should be >= pref if(words[i][0] == pref[0] && pref.length() <= words[i].length()){ int j = 0; while(j<words[i].length() && j < pref.length() && pref[j] == words[i][j]){ j++; } // If the whole prefix found then count if(j == pref.length()){ count++; } } } return count; } }; ``` ![image.png](https://assets.leetcode.com/users/images/8f45f11e-c625-4599-9b28-e830bc2c66d0_1724569032.8579876.png)
4
0
['Array', 'String', 'String Matching', 'C++']
0
counting-words-with-a-given-prefix
simple and easy Python solution 😍❤️‍🔥
simple-and-easy-python-solution-by-shish-do38
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
shishirRsiam
NORMAL
2024-07-26T18:16:57.160326+00:00
2024-07-26T18:16:57.160356+00:00
282
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n# Code\n```\nclass Solution(object):\n def prefixCount(self, words, pref):\n ans = 0\n for s in words:\n if s.startswith(pref):\n ans += 1\n return ans\n```
4
0
['Array', 'String', 'String Matching', 'Python', 'Python3']
3
counting-words-with-a-given-prefix
[Python3] Brute Force - Simple Solution
python3-brute-force-simple-solution-by-d-iimi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
dolong2110
NORMAL
2024-03-18T08:55:21.173820+00:00
2024-03-18T08:55:21.173863+00:00
212
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n##### 1. Brute-Force\n```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n m = len(pref)\n cnt = 0\n for word in words:\n if word[:m] == pref: cnt += 1\n return cnt\n```\n\n- Time complexity: $$O(N * M)$$ with `N` is length of `words` and `M` is length of `pref`\n\n- Space complexity: $$O(1)$$\n\n##### 2. 1-line\n```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(1 for word in words if word.startswith(pref))\n```\n- Time complexity: $$O(N * M)$$ with `N` is length of `words` and `M` is length of `pref`\n\n- Space complexity: $$O(1)$$
4
0
['Array', 'String', 'String Matching', 'Python3']
0
counting-words-with-a-given-prefix
Beats 100% of users with C++ || Step By Step Explain || Easy to Understand ||
beats-100-of-users-with-c-step-by-step-e-bljc
Abhiraj pratap Singh\n\n---\n\n# UPVOTE \n\n----\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n- The given code seems to be de
abhirajpratapsingh
NORMAL
2024-01-28T05:22:44.667873+00:00
2024-01-28T05:22:44.667913+00:00
165
false
# Abhiraj pratap Singh\n\n---\n\n# UPVOTE \n\n----\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The given code seems to be defining a class Solution with two functions: isPrefix and prefixCount. The isPrefix function checks if a given string pref is a prefix of another string s, and the prefixCount function counts the number of strings in a vector words that have the specified prefix pref.\n\n---\n\n![Screenshot (47).png](https://assets.leetcode.com/users/images/fa9c4313-c0ae-4162-96d0-44f4c4e2487d_1706419130.0879095.png)\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The isPrefix function iterates through the characters of both strings (s and pref) and checks if they match for the first m characters (where m is the length of the prefix pref).\n2. The prefixCount function uses the isPrefix function to iterate through the vector of words (words) and increments the count whenever a word has the specified prefix.\n\n\n---\n\n\n# Complexity\n\n- **Time complexity:** Let\'s analyze the time complexity of each function:\n - For the isPrefix function, the time complexity is O(m) where \'m\' is the length of the prefix string.\n - For the prefixCount function, it iterates through each word in the vector, and for each word, it calls the isPrefix function. Therefore, the overall time complexity is O(n * m), where \'n\' is the number of words in the vector and \'m\' is the length of the prefix string.\n\n- **Space complexity:** The space complexity is O(1) for both functions as they use a constant amount of extra space regardless of the input size.\n\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isPrefix(string s,string pref)\n {\n int n=s.length();\n int m=pref.length();\n if(n<m)\n return false;\n for(int i=0;i<m;i++)\n {\n if(pref[i]!=s[i])\n return false;\n }\n return true;\n }\n int prefixCount(vector<string>& words, string pref) \n {\n int count=0;\n for(int i=0;i<words.size();i++)\n {\n if( isPrefix(words[i],pref) )\n count++;\n }\n return count;\n }\n};\n```\n\n---\n\n# if you like the solution please UPVOTE it\n\n---\n\n![discord-discordgifemoji.gif](https://assets.leetcode.com/users/images/3724c92f-dd04-4738-b84f-d07622e5ee85_1706419343.2128263.gif)\n\n![fucking-die-redditor-stupid-cuck-funny-cat.gif](https://assets.leetcode.com/users/images/20ab3747-5112-4f1a-ad67-6da96f53b4eb_1706419345.5493877.gif)\n\n---
4
0
['Array', 'String', 'String Matching', 'C++']
0
counting-words-with-a-given-prefix
easy java solution.....
easy-java-solution-by-21241a0595-jzce
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
21241A0595
NORMAL
2023-05-23T09:51:16.790246+00:00
2023-05-23T09:51:16.790282+00:00
228
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count=0;\n for(int i=0;i<words.length;i++)\n {\n if(words[i].startsWith(pref))\n count++;\n }\n return count;\n }\n}\n```
4
0
['Java']
1
counting-words-with-a-given-prefix
JAVA Beginner Friendly fast solution
java-beginner-friendly-fast-solution-by-00s8k
class Solution {\n public int prefixCount(String[] words, String pref) {\n int count =0 ;\n for(int i = 0 ;i<words.length ;i++){\n int l =
yudhisthirsinghcse2023
NORMAL
2022-05-13T08:43:45.397857+00:00
2022-05-13T08:43:45.397904+00:00
412
false
class Solution {\n public int prefixCount(String[] words, String pref) {\n int count =0 ;\n for(int i = 0 ;i<words.length ;i++){\n int l = pref.length();\n if(l<=words[i].length()){\n String sub = words[i].substring(0,l);\n if(pref.equals(sub))\n count++;\n }\n }\n return count;\n }\n}
4
1
['Java']
1
counting-words-with-a-given-prefix
c++ solution using substr
c-solution-using-substr-by-varchirag-d2ni
\'\'\'\nclass Solution {\npublic:\n int prefixCount(vector& words, string pref) {\n int ans=0;\n for(auto x:words){\n if(x.substr(0,
varchirag
NORMAL
2022-03-14T11:09:28.509860+00:00
2022-03-14T11:09:28.509891+00:00
506
false
\'\'\'\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int ans=0;\n for(auto x:words){\n if(x.substr(0,pref.size()) == pref)\n {\n ans++;\n }\n }\n return ans;\n }\n};
4
0
['String', 'C', 'C++']
0
counting-words-with-a-given-prefix
CAN'T BE MORE EASY
cant-be-more-easy-by-ankit088-d1ix
class Solution {\npublic:\n int prefixCount(vector& words, string pref) {\n \n int n = words.size(); \n int k = pref.length(); \n
ankit088
NORMAL
2022-02-27T04:05:43.482156+00:00
2022-02-27T04:05:43.482210+00:00
149
false
class Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n \n int n = words.size(); \n int k = pref.length(); \n \n int count = 0; \n for(int i =0; i<n; i++)\n {\n if(words[i].length() >= k)\n {\n if(words[i].substr(0,k) == pref)\n count++; \n }\n }\n return count; \n }\n};
4
2
[]
0
counting-words-with-a-given-prefix
simple solution
simple-solution-by-ankush093-uf9r
\nclass Solution {\n bool check(string &s , string &p){\n if(s.length() < p.length())\n return false;\n int i = 0;\n fo
Ankush093
NORMAL
2022-02-27T04:02:28.516815+00:00
2022-02-27T04:02:28.516844+00:00
448
false
```\nclass Solution {\n bool check(string &s , string &p){\n if(s.length() < p.length())\n return false;\n int i = 0;\n for(i = 0 ; i < p.length() ; i++){\n if(p[i] != s[i])\n return false;\n }\n return true;\n }\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int cnt = 0;\n int n = words.size();\n for(int i = 0 ; i < n ; i++){\n if(check(words[i] , pref))\n cnt++;\n }\n return cnt;\n }\n};\n```
4
0
['C++']
0
counting-words-with-a-given-prefix
❤ Easy, Fast & Understandable Python Solution
easy-fast-understandable-python-solution-n1pi
IntuitionThe intuition for this problem is to check each word in the list to see if it starts with the given prefix. We can use pythons startswith() method to a
ehewes
NORMAL
2025-01-09T15:07:09.830026+00:00
2025-01-09T15:07:09.830026+00:00
13
false
# Intuition The intuition for this problem is to check each word in the list to see if it starts with the given prefix. We can use pythons ``startswith()`` method to approach this. # Approach Iterate through each word in the ``words`` list. Then we use the ``startswith()`` method to check the specified prefix. Then we add to the count how many times we've seen a match. # Complexity - Time complexity: O(N∗M) - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: count = 0 for word in words: if word.startswith(pref): count += 1 return count ``` Please **upvote** 😄❤
3
0
['Array', 'String', 'String Matching', 'Python3']
0
counting-words-with-a-given-prefix
100% Beats | Easiest Solution | 2 Approaches | C++
100-beats-easiest-solution-c-by-vineetve-1j6m
IntuitionApproachComplexity Time complexity: Space complexity: Code
vineetvermaa30
NORMAL
2025-01-09T14:28:55.343465+00:00
2025-01-09T14:33:01.312314+00:00
17
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count=0; for(auto word: words){ for(int i=0; i<pref.size(); i++){ if(pref[i] != word[i]) break; if(i==pref.size()-1) count++; } } return count; // METHOD-2: Using substring // int count=0; // for(auto word: words) // if(word.substr(0, pref.length()) == pref) count++; // return count; } }; ```
3
0
['C++']
0
counting-words-with-a-given-prefix
COUNT NUMBER OF PREFIXES IN A LIST
count-number-of-prefixes-in-a-list-by-po-bedi
IntuitionThe problem involves counting the number of words in a list that start with a given prefix. A straightforward way to solve this is by iterating through
Poornasri
NORMAL
2025-01-09T14:19:41.420714+00:00
2025-01-09T14:19:41.420714+00:00
15
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem involves counting the number of words in a list that start with a given prefix. A straightforward way to solve this is by iterating through the list and checking each word's prefix using slicing. This allows us to efficiently determine whether the prefix matches. # Approach <!-- Describe your approach to solving the problem. --> 1. Calculate the length of the prefix using len(pref). 2. Initialize a counter 'count' to zero. 3. Iterate over each word in the list: - Slice the first 'size' characters from the word. - for atlast and size=2 slicing is done 0 to 1 index so [:size] - Compare the slice with 'pref'. If they match, increment 'count'. 4. Return the final count. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * m) where n is the number of words, and m is the length of the prefix. Outer Loop (for word in words): The loop iterates through the list of words, so it runs 'n' times, where 'n' is the number of words in the list. Prefix Comparison (word[:size] == pref): - The slicing operation word[:size] takes O(m), where 'm' is the length of the prefix (size). - The equality check '== pref' also compares up to 'm' characters. - Therefore, this operation has a time complexity of O(m). - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) since no additional data structures are used # Code ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: size=len(pref) count=0 for word in words: if word[:size]==pref: count=count+1 return count ```
3
0
['Array', 'String', 'String Matching', 'Python3']
0
counting-words-with-a-given-prefix
very simple solution
very-simple-solution-by-shashwat1915-g4vc
Code
shashwat1915
NORMAL
2025-01-09T12:55:12.055254+00:00
2025-01-09T12:55:12.055254+00:00
17
false
# Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int ans=0; for(auto &x:words){ if(x.size()<pref.size()) continue; if(x[0]!=pref[0]) continue; if(x.substr(0,pref.size())==pref) ans++; } return ans; } }; ```
3
0
['C++']
0
counting-words-with-a-given-prefix
Best Code with Optimum Complexity 🚀
best-code-with-optimum-complexity-f-by-h-mpzc
IntuitionThe problem involves checking if a prefix exists in a set of strings. Since we only need to compare the prefix with the beginning of each word, we can
hamza_p2
NORMAL
2025-01-09T11:10:39.792936+00:00
2025-01-09T11:13:11.289988+00:00
17
false
# Intuition The problem involves checking if a prefix exists in a set of strings. Since we only need to compare the prefix with the beginning of each word, we can iterate through the array and check each word for the required condition. # Approach Iterate through each word in the array. Use the startsWith() method of the String class to check if the current word begins with the given prefix. If the condition is true, increment a counter to keep track of the number of matches. Return the counter after iterating through the array. This approach is straightforward and leverages Java's built-in startsWith() method for efficiency and simplicity. # Complexity Time Complexity: The time complexity is O(n * m), where: n: Number of words in the array (words.length). m: Length of the prefix (pref.length), since startsWith checks up to the length of the prefix for each word. Space Complexity: The space complexity is O(1) because we use only a constant amount of extra space for the counter. # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int num=0; for(String word:words){ int i; if(word.startsWith(pref)){ num++; } } return num; } } ```
3
0
['Java']
2
counting-words-with-a-given-prefix
Beats 100.00% ✅✅ | Easy Code | Brute Force🔥
beats-10000-easy-code-brute-force-by-ans-i5ty
Intuition There is not so much to observe, just brute force and check for every string present in words, whether it contains "pref" as prefix or not. For exa
anshul169
NORMAL
2025-01-09T06:00:55.831704+00:00
2025-01-09T06:23:06.543048+00:00
18
false
![Screenshot 2025-01-09 110411.png](https://assets.leetcode.com/users/images/e5fe5475-72ae-43a0-ba46-193f3f6f8db1_1736401508.4626627.png) # Intuition - There is not so much to observe, just brute force and check for every string present in words, whether it contains *"pref"* as prefix or not. - For example a string from words is *"str"*. Assume **n = size of "str"**, **m = size of "pref"**, now if n < m, that means string *"str"* can never contain whole *"pref"* as a prefix. - If n >= m, that means we only need to check whether the first m characters of *"str"* are same as *"pref"* or not, so for this we just brute force over the length of *"pref"*. # Approach 1. Outer loop is for all the strings present in words. 2. If n < m so no need to check we just skip this string, otherwise if n >= m, just loop for prefix and check whether **str[i] == pref[i]** or not, if at any point they dont match, that means *"pref"* is not present as prefix, so we just break. 3. Otherwise if we reach the end , i.e **i == m-1** and still we are inside the loop that means all character till now are same in *"str"* and *"pref"*, so we increment our answer. 4. Finally return our answer. # Complexity - Time complexity: 1. We loop over all strings present in words, and for each string we again loop for size of *"pref"*, to check whether *"pref"* is present as prefix or not. 2. **T.C - O(words.size() * pref.size())** - Space complexity: 1. No additional space has been used for solving the problem. 2. **S.C - O(1)** # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int ans = 0; for(auto str : words){ int n = str.size(),m = pref.size(); if(n < m)continue; for(int i=0;i<m;i++){ if(str[i] != pref[i]){ break; } if(i == m-1)ans++; } } return ans; } }; ```
3
0
['String', 'String Matching', 'C++']
0
counting-words-with-a-given-prefix
Counting Words With a Given Prefix
counting-words-with-a-given-prefix-by-ya-open
Code
Yadav_Akash_
NORMAL
2025-01-09T05:28:18.264909+00:00
2025-01-09T05:28:18.264909+00:00
12
false
# Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int c=0; for(int i=0;i<words.length;i++){ if(words[i].startsWith(pref)){ c++; } } return c; } } ```
3
0
['Java']
0
counting-words-with-a-given-prefix
✅ Easy to understand | Beats 100% ✅
easy-to-understand-beats-100-by-yogeshm0-w5px
Intuition We can iterate through each word in the list and check if the prefix matches the beginning of the word. The Python string method .startswith() is e
yogeshm01
NORMAL
2025-01-09T04:44:35.064506+00:00
2025-01-09T04:44:35.064506+00:00
13
false
# Intuition - We can **iterate** through each word in the list and check if the prefix matches the beginning of the word. - The Python string method **.startswith()** is efficient for this purpose. # Approach 1. Initialize a ***counter*** to 0. 2. Iterate through each word in the words list. 3. For each word, check if it starts with the given pref. In Python, we can use the *startswith()* method for this. 4. If the word starts with the prefix, increment the counter. 5. After iterating through all words, return the counter. # Complexity - Time complexity: Checking if a word starts with a prefix using .startswith() is O(m), where 𝑚 is the length of the prefix. For a list of 𝑛 words, each of average length 𝑘, the total complexity is: O(n⋅m) - Space complexity: The solution does not use any additional data structures, and the space used is constant, O(1), apart from the input. # Code ```python [] class Solution(object): def prefixCount(self, words, pref): count = 0 for word in words: if word.startswith(pref): count += 1 return count ```
3
0
['Python']
0
counting-words-with-a-given-prefix
C# Solution for Counting Words With a Given Prefix Problem
c-solution-for-counting-words-with-a-giv-5zz1
IntuitionThe problem is about counting the number of words in the array words that start with a given prefix pref. A prefix is a contiguous substring starting f
Aman_Raj_Sinha
NORMAL
2025-01-09T04:17:49.311046+00:00
2025-01-09T04:17:49.311046+00:00
63
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem is about counting the number of words in the array words that start with a given prefix pref. A prefix is a contiguous substring starting from the first character of a word. In C#, the StartsWith method provides a straightforward way to check if a string begins with a specified substring, so the solution relies on iterating through the array and applying this method to each word. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize a Counter: • Create a variable count to keep track of the number of words that match the prefix. 2. Iterate Through the words Array: • Use a foreach loop to traverse each word in the array. • For each word, use the StartsWith method to check if the word starts with pref. 3. Update the Counter: • If word.StartsWith(pref) returns true, increment the count. 4. Return the Count: • After iterating through all the words, return the final value of count. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n * m), where: • n : The number of words in the array (words.Length). • m : The maximum length of a word or the prefix (Math.Min(word.Length, pref.Length) for each comparison). Explanation: • For each word in the words array, the StartsWith method compares the characters of the prefix pref with the beginning of the word, which takes O(m) . • Since the loop iterates through n words, the total time complexity is O(n x m) . - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) Explanation: • The solution uses a constant amount of extra space for variables like count and loop iterators. • The StartsWith method does not require additional memory. # Code ```csharp [] public class Solution { public int PrefixCount(string[] words, string pref) { int count = 0; foreach (string word in words) { if (word.StartsWith(pref)) { count++; } } return count; } } ```
3
0
['C#']
0
counting-words-with-a-given-prefix
Easy For Loop Solution
easy-for-loop-solution-by-samir04-iv5p
null
Samir04
NORMAL
2025-01-09T03:59:45.782079+00:00
2025-01-09T03:59:45.782079+00:00
110
false
```java [] class Solution { public int prefixCount(String[] words, String pref) { int count =0; for(String word : words){ if(word.indexOf(pref) == 0){ count+=1; } } return count; } } ``` ```python3 [] class Solution: def prefixCount(self, words, pref): count = 0 for word in words: if word.find(pref) == 0: count += 1 return count ```
3
0
['Java', 'Python3']
0
counting-words-with-a-given-prefix
✅ Beginner Friendly | Easy | Beats 100% | Detailed Video Explanation🔥
beginner-friendly-easy-beats-100-detaile-m4gh
IntuitionThe problem involves counting words that start with a given prefix. My first thought was to iterate through the list of words and check each one to see
sahilpcs
NORMAL
2025-01-09T03:37:42.222212+00:00
2025-01-09T03:37:42.222212+00:00
101
false
# Intuition The problem involves counting words that start with a given prefix. My first thought was to iterate through the list of words and check each one to see if it begins with the specified prefix. This can be achieved efficiently using the `startsWith` method provided in Java's `String` class. # Approach 1. Initialize a counter to keep track of the words that start with the given prefix. 2. Iterate through the array of words. 3. For each word, use the `startsWith` method to check if it begins with the prefix. 4. If the condition is true, increment the counter. 5. Return the counter after processing all the words. This approach is simple and leverages Java's built-in method for prefix matching, ensuring clarity and correctness. # Complexity - Time complexity: The time complexity is $$O(n \cdot m)$$, where: - $$n$$ is the number of words in the array. - $$m$$ is the length of the prefix. Each word requires a comparison of its first $$m$$ characters with the prefix. - Space complexity: The space complexity is $$O(1)$$ because no extra space is used apart from a few variables for iteration and counting. # Code ```java [] class Solution { // Method to count the number of words in the array `words` that start with the prefix `pref` public int prefixCount(String[] words, String pref) { // Get the total number of words in the input array int n = words.length; // Initialize a counter to track the number of words starting with the given prefix int count = 0; // Iterate through each word in the array for (int i = 0; i < n; i++) { // Access the current word from the array String word = words[i]; // Check if the current word starts with the specified prefix if (word.startsWith(pref)) { // Increment the counter if the condition is true count++; } } // Return the total count of words starting with the prefix return count; } } ``` LeetCode 2185 Counting Words With a Given Prefix | Easy | String Matching | Asked in Google https://youtu.be/sbDVQcs0hhg
3
0
['Array', 'String', 'String Matching', 'Java']
2
counting-words-with-a-given-prefix
Java🍵|Brute Force✅|Easy🔥
javabrute-forceeasy-by-mani-26-injs
Complexity Time complexity: O(n * m) Space complexity: O(1) Code
mani-26
NORMAL
2025-01-09T03:22:03.239059+00:00
2025-01-09T03:22:03.239059+00:00
21
false
# Complexity - Time complexity: **O(n * m)** - Space complexity: **O(1)** # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int n = words.length; int m = pref.length(); int count = 0; for (String word: words) { if (m > word.length()) continue; else { boolean flag = true; for (int k = 0; k < m; k++) { if (pref.charAt(k) != word.charAt(k)) { flag = false; break; } } if (flag) { count++; } } } return count; } } ```
3
0
['Array', 'String', 'Java']
0
counting-words-with-a-given-prefix
2185. Counting Words With a Given Prefix
2185-counting-words-with-a-given-prefix-xmro6
IntuitionApproachComplexity Time complexity: Space complexity: Code
9121892475
NORMAL
2025-01-09T00:54:40.062734+00:00
2025-01-09T00:54:40.062734+00:00
110
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int count = 0; for (String word : words) { if (word.startsWith(pref)) { count++; } } return count; } } ```
3
0
['Java']
0
counting-words-with-a-given-prefix
Counting words with a given prefix using Java || Beats 100.00%
counting-words-with-a-given-prefix-using-nqt4
IntuitionIn the given question this is clearly mention that Return the number of strings in words that have pref as a prefix. A prefix of a string s is any lead
kundan2026
NORMAL
2025-01-09T00:21:51.346078+00:00
2025-01-09T00:21:51.346078+00:00
95
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> In the given question this is clearly mention that Return the **number of strings** in words that have pref as a prefix. A prefix of a string s is any leading contiguous substring of s. # Approach <!-- Describe your approach to solving the problem. --> - **Parameters:** This method takes two parameters: - words: An array of strings representing the words to be checked. - pref: A string representing the prefix that we want to check each word for. - **Logic:** - The method initializes a count variable to zero. This will keep track of how many words in the words array start with the pref string. - The method iterates over each word in the words array. For each word, it checks if the word starts with the pref prefix using the startsWith method (which returns true if the word starts with the given prefix). - If the word starts with the prefix, the method increments the count by 1. - After all words are checked, the method returns the final count, which represents the number of words that start with the given prefix. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: (1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int Count(String[] words, String pref) { int count=0; int len=words.length; for(int i=0;i<len;i++){ if(words[i].startsWith(pref)){ count++; } } return count; } public int prefixCount(String[] words, String pref) { return Count(words,pref); } } ```
3
0
['Array', 'String', 'String Matching', 'Java']
0
counting-words-with-a-given-prefix
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-kmru
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
shishirRsiam
NORMAL
2024-07-26T18:13:05.949160+00:00
2024-07-26T18:13:05.949182+00:00
297
false
\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n\n\n# Code\n```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) \n {\n int ans = 0;\n for(auto s:words)\n if(s.find(pref) == 0) ans += 1;\n return ans;\n }\n};\n```
3
0
['Array', 'String', 'String Matching', 'C++']
3
counting-words-with-a-given-prefix
💢Faster✅💯 Lesser C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 💯
faster-lesser-cpython3javacpythonexplain-7f26
IntuitionApproach JavaScript Code --> https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502551628 C++ Code --> https://leetcode.com/
Edwards310
NORMAL
2024-01-23T13:10:26.888221+00:00
2025-01-09T05:00:07.523532+00:00
52
false
![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/9fc46acb-7ba4-42e1-864c-3b0e7e0e82b6_1730795144.4340796.jpeg) # Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your first thoughts on how to solve this problem. --> - ***JavaScript Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502551628 - ***C++ Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1154427835 - ***Python3 Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502526439 - ***Java Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1154428180 - ***C Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502520140 - ***Python Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1271443012 - ***C# Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502558869 - ***Go Code -->*** https://leetcode.com/problems/counting-words-with-a-given-prefix/submissions/1502556696 <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(N) - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code # Upvote bhi kardo yaar ... Like hi to manga hai bass dedo na yaar... ![th.jpeg](https://assets.leetcode.com/users/images/e4a03b1d-6e7d-4ef7-8287-2172f183be90_1706015421.6951764.jpeg)
3
0
['Array', 'String', 'C', 'String Matching', 'Python', 'C++', 'Java', 'Go', 'Python3', 'C#']
1
counting-words-with-a-given-prefix
Easy Solution in JAVA
easy-solution-in-java-by-717821p359kce-db8d
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
717821p359kce
NORMAL
2023-08-02T12:44:05.445628+00:00
2023-08-02T12:44:05.445661+00:00
280
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(s.length)\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int prefixCount(String[] s, String t) {\n int n=s.length;\n int count=0;\n int m=t.length();\n for(int i=0;i<n;i++)\n {\n if(s[i].startsWith(t))\n count++;\n }\n return count;\n }\n}\n```
3
0
['Java']
3
counting-words-with-a-given-prefix
Simplest Python solution. Use startswith
simplest-python-solution-use-startswith-duri2
\n\n# Code\n\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n cnt = 0\n for s in words:\n if s.starts
tryingall
NORMAL
2023-06-25T18:28:01.386343+00:00
2023-06-25T18:28:01.386377+00:00
614
false
\n\n# Code\n```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n cnt = 0\n for s in words:\n if s.startswith(pref):\n cnt += 1\n return cnt\n```
3
0
['Python3']
0
counting-words-with-a-given-prefix
Simple | Easy | JAVA Solution (100%)
simple-easy-java-solution-100-by-pranavi-9lmg
\n# Code\n\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count=0;\n for(int i=0;i<words.length;i++)\n
pranavibhute
NORMAL
2023-05-17T13:03:38.284140+00:00
2023-05-17T13:12:30.382882+00:00
239
false
\n# Code\n```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count=0;\n for(int i=0;i<words.length;i++)\n {\n if(words[i].startsWith(pref))count++;\n }\n return count;\n }\n}\n```
3
0
['String', 'String Matching', 'Counting', 'Java']
0
counting-words-with-a-given-prefix
Counting words with a given prefix
counting-words-with-a-given-prefix-by-hi-9htc
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
himshrivas
NORMAL
2023-03-02T11:44:13.685664+00:00
2023-03-02T11:44:13.685713+00:00
407
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n![countingwords.PNG](https://assets.leetcode.com/users/images/8d68c99b-176b-4804-a2bf-630bc38328e6_1677757448.8018465.png)\n\n# Code\n```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n count=0\n for i in words:\n if pref in i and i.index(pref)==0:\n print(i)\n count+=1\n return count\n```
3
0
['Python3']
0
counting-words-with-a-given-prefix
C++ Solution || Simple Approach
c-solution-simple-approach-by-asad_sarwa-rwv5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Asad_Sarwar
NORMAL
2023-02-08T14:50:06.573249+00:00
2023-02-08T14:50:06.573309+00:00
497
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n \n\n int prefix_size = pref.size();\n int n=words.size();\n int count = 0;\n for (int i = 0; i < n; i++)\n {\n string s1 = words[i].substr(0, prefix_size);\n if (s1 == pref)\n {\n count++;\n }\n }\n return count;\n\n\n }\n};\n```
3
0
['C++']
0
counting-words-with-a-given-prefix
Java
java-by-aahanaganjewar17-dpyv
\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for (String word: words) {\n if (word.
aahanaganjewar17
NORMAL
2022-11-27T17:43:49.769958+00:00
2022-11-27T17:43:49.769998+00:00
772
false
```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for (String word: words) {\n if (word.indexOf(pref) == 0) {\n count++;\n }\n }\n return count;\n }\n}\n```
3
0
['Java']
1
counting-words-with-a-given-prefix
Java Simple Solution
java-simple-solution-by-janhvi__28-t3td
\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for(int i = 0; i<words.length; i++){\n if(word
Janhvi__28
NORMAL
2022-10-20T18:54:17.659006+00:00
2022-10-20T18:54:17.659035+00:00
851
false
```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for(int i = 0; i<words.length; i++){\n if(words[i].startsWith(pref)){\n count++;\n }\n }\n return count;\n }\n}\n\n\n```
3
0
['Java']
0
counting-words-with-a-given-prefix
Beginner friendly [Java/JavaScript/Python] Solution
beginner-friendly-javajavascriptpython-s-77d9
Time Complexity : O(n*m)\nJava\n\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for(String word :
HimanshuBhoir
NORMAL
2022-03-06T03:50:25.179711+00:00
2022-08-31T01:36:56.336808+00:00
323
false
**Time Complexity : O(n*m)**\n**Java**\n```\nclass Solution {\n public int prefixCount(String[] words, String pref) {\n int count = 0;\n for(String word : words){\n if(word.indexOf(pref) == 0) count++; \n }\n return count;\n }\n}\n```\n**JavaScript**\n```\nvar prefixCount = function(words, pref) {\n let count = 0;\n for(let word of words){\n if(word.indexOf(pref) == 0) count++;\n }\n return count;\n};\n```\n**Python**\n```\nclass Solution(object):\n def prefixCount(self, words, pref):\n count = 0\n for word in words:\n if pref in word and word.index(pref) == 0:\n count += 1\n return count\n```
3
0
['Python', 'Java', 'JavaScript']
1
counting-words-with-a-given-prefix
Python 1 Liner Solution
python-1-liner-solution-by-ancoderr-uvus
\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(word.find(pref) == 0 for word in words)\n
ancoderr
NORMAL
2022-02-27T06:16:52.425424+00:00
2022-02-27T06:16:52.425460+00:00
653
false
```\nclass Solution:\n def prefixCount(self, words: List[str], pref: str) -> int:\n return sum(word.find(pref) == 0 for word in words)\n```
3
0
['Python', 'Python3']
1
counting-words-with-a-given-prefix
Simple, Short | C++
simple-short-c-by-krishnakant01-d0k5
Counting Words With a Given Prefix\nTravel each word in words and check if it\'s size is greater or equal to size if prefix and compare the substring of length
krishnakant01
NORMAL
2022-02-27T05:08:17.549848+00:00
2022-02-27T05:08:17.549875+00:00
136
false
**Counting Words With a Given Prefix**\nTravel each word in words and check if it\'s size is greater or equal to size if prefix and compare the substring of length n(size of prefix) with prefix, if equal increase count.\n\n```\nint prefixCount(vector<string>& words, string p) {\n int n=p.size();\n int ans=0;\n for(auto w:words)\n {\n if(w.size()>=n and w.substr(0,n)==p)\n {\n ans++;\n }\n }\n return ans;\n }\n```
3
0
['String', 'C']
0
counting-words-with-a-given-prefix
Easy c++ solution | Brute force
easy-c-solution-brute-force-by-_pinocchi-o1n1
\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int count = 0;\n for(auto it : words){\n bool
_Pinocchio
NORMAL
2022-02-27T04:59:20.647071+00:00
2022-02-27T04:59:20.647097+00:00
202
false
```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int count = 0;\n for(auto it : words){\n bool flag = true;\n for(int i=0;i<pref.size();i++){\n if(pref[i] != it[i]) {flag = false; break;}\n }\n if(flag) count++;\n }\n return count;\n }\n};\n```
3
0
['C', 'C++']
0
counting-words-with-a-given-prefix
JavaScript "startsWith" method
javascript-startswith-method-by-shashwat-sbqb
\nvar prefixCount = function(words, pref) {\n let count = 0;\n for(let word of words) {\n if(word.startsWith(pref)) count++;\n }\n return cou
ShashwatBangar
NORMAL
2022-02-27T04:37:26.596971+00:00
2022-02-28T08:09:52.493403+00:00
201
false
```\nvar prefixCount = function(words, pref) {\n let count = 0;\n for(let word of words) {\n if(word.startsWith(pref)) count++;\n }\n return count;\n};\n```
3
1
['JavaScript']
0
counting-words-with-a-given-prefix
C++ Solution
c-solution-by-raman_kumar0-23yv
\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int ans = 0;\n for(int i = 0; i < words.size(); i++)
Raman_Kumar0
NORMAL
2022-02-27T04:01:10.983184+00:00
2022-02-27T04:01:10.983227+00:00
305
false
```\nclass Solution {\npublic:\n int prefixCount(vector<string>& words, string pref) {\n int ans = 0;\n for(int i = 0; i < words.size(); i++){\n int j = 0;\n int n = words[i].length();\n if(n<pref.length())continue;\n {\n while(j<pref.length()){\n if(pref[j] == words[i][j])\n j++;\n }\n else \n break; \n }\n if(j==pref.length())ans++;\n }\n return ans;\n }\n};\n```
3
0
[]
0
counting-words-with-a-given-prefix
Easy and Simple Solution
easy-solution-java-by-mayankluthyagi-2r78
CodePlease Like ❤️IntuitionThe problem asks to count how many strings in the list words start with the given prefix pref. The approach is straightforward: itera
mayankluthyagi
NORMAL
2025-01-23T03:50:29.699753+00:00
2025-01-23T16:15:00.194609+00:00
6
false
# Code ```java class Solution { public int prefixCount(String[] words, String pref) { int res = 0; for (String ch : words) { if (ch.startsWith(pref)) { res++; } } return res; } } ``` # Please Like ❤️ ![Please Like](https://media.tenor.com/heEyHbV8iaUAAAAM/puss-in-boots-shrek.gif) # Intuition The problem asks to count how many strings in the list `words` start with the given prefix `pref`. The approach is straightforward: iterate through each word and check if it starts with the prefix. # Approach 1. Iterate through each word in the `words` array. 2. Use the `startsWith()` method to check if each word starts with the given prefix `pref`. 3. Count the number of words that satisfy the condition. # Complexity - **Time complexity**: $$O(n \cdot m)$$, where $$n$$ is the number of words and $$m$$ is the average length of the words: - The `startsWith()` method takes linear time in the length of the word, and we check this for all words. - **Space complexity**: $$O(1)$$, since we only use a few variables for counting.
2
0
['Java']
0
counting-words-with-a-given-prefix
✅ Beats 100% || C++ || 0ms
beats-100-c-0ms-by-ojasks-0gz8
IntuitionIf it is a prefix its index will be starting from 0.Approach Put the word (string) through a loop and find the first occurence of the prefix in the thi
ojasks
NORMAL
2025-01-22T09:37:12.699529+00:00
2025-01-22T09:37:12.699529+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> *If it is a prefix its index will be starting from 0.* # Approach <!-- Describe your approach to solving the problem. --> * Put the word (string) through a loop and find the first occurence of the prefix in the this particular string and store that index if that index is == 0 then increase the count of the total no of strings having the prefix in them and then return it. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> #### O(n.m) n -> no. of words m -> avg. length of an word - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> #### O(1) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count=0; for(auto word: words){ size_t index= word.find(pref); if(index==0){ count++; } } return count; } }; ```
2
0
['C++']
0
counting-words-with-a-given-prefix
Java Solution with Easy & Beginner-friendly code
java-solution-with-easy-beginner-friendl-tpw1
Code
Ritik_bohra
NORMAL
2025-01-09T18:04:48.815072+00:00
2025-01-09T18:04:48.815072+00:00
8
false
# Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int ans = 0; int lengthOfPref = pref.length(); for(int i =0; i<words.length; i++){ if((words[i].contains(pref)) && (words[i].substring(0, lengthOfPref).equals(pref))){ ans +=1; } } return ans; } } ```
2
0
['Java']
1
counting-words-with-a-given-prefix
Simple using Find function Beats 100%.
simple-using-find-function-beats-100-by-7gvjy
IntuitionHey,as we know the find function returns the first occurence of a pattern in a string.ApproachWe iterate over each word and use the find function if th
YoSTMxl7sY
NORMAL
2025-01-09T17:50:52.298259+00:00
2025-01-09T17:50:52.298259+00:00
7
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Hey,as we know the find function returns the first occurence of a pattern in a string. # Approach <!-- Describe your approach to solving the problem. --> We iterate over each word and use the find function if the first occurence is 0 we increment the count. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n*m) as find function is involved. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1) # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int c=0; for(int i=0;i<words.size();i++) { if(words[i].find(pref)==0) c++; } return c; } }; ```
2
0
['C++']
1
counting-words-with-a-given-prefix
Easy Java Solution - Beats 100% (Runtime 0ms)
easy-java-solution-beats-100-runtime-0ms-0dru
Complexity Time complexity: O(n), where n = words.length Space complexity: O(1) Code
ruch21
NORMAL
2025-01-09T17:45:54.056287+00:00
2025-01-09T17:45:54.056287+00:00
14
false
# Complexity - Time complexity: $$O(n)$$, where n = words.length - Space complexity: $$O(1)$$ # Code ```java [] class Solution { public int prefixCount(String[] words, String pref) { int ans = 0; for(int i=0; i<words.length; i++) { if(words[i].indexOf(pref) == 0) { ans++; } } return ans; } } ```
2
0
['Java']
1
counting-words-with-a-given-prefix
<Count Words with a Given Prefix in a List>
count-words-with-a-given-prefix-in-a-lis-k0qt
IntuitionThe problem is about counting how many words start with a given prefix. To solve this, we can simply check the beginning of each word in the list to se
ankita_molak21
NORMAL
2025-01-09T17:43:30.776906+00:00
2025-01-09T17:43:30.776906+00:00
7
false
# Intuition The problem is about counting how many words start with a given prefix. To solve this, we can simply check the beginning of each word in the list to see if it matches the prefix. <!-- Describe your first thoughts on how to solve this problem. --> # Approach 1)Loop through each word in the list. 2)Use the substr function to extract the prefix of the word, and compare it with the given prefix. 3)If they match, increase the count. 4)Return the total count after processing all the words. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n⋅k), where n is the number of words and k is the average length of the prefix. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: - O(1), as no additional space is used. <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] #include <string> #include <vector> using namespace std; class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; for (const string& word : words) { if (word.substr(0, pref.size()) == pref) { count++; } } return count; } }; ```
2
0
['C++']
0
counting-words-with-a-given-prefix
Easy python solution beats 100.00% submissions
easy-python-solution-beats-10000-submiss-x1zc
ApproachCount the number of strings in the words list that start with the given prefix. For each word in the list, we check whether the prefix matches the first
poojithat
NORMAL
2025-01-09T17:19:42.690238+00:00
2025-01-09T17:19:42.690238+00:00
3
false
# Approach Count the number of strings in the words list that start with the given prefix. For each word in the list, we check whether the prefix matches the first n characters of the word, where n is the length of pref. # Complexity Time Complexity: O(N×M), where: N is the number of words in the list. M is the average length of the words. Each word comparison involves checking up to the length of the prefix. M in the worst case. Space Complexity: O(1) as no additional space proportional to the input size is used. # Code ```python3 [] class Solution: def prefixCount(self, words: List[str], pref: str) -> int: result = 0 n = len(pref) for i in range(len(words)): if(words[i][0:n] == pref): result += 1 return result ```
2
0
['Python3']
0
counting-words-with-a-given-prefix
Counting Words | Simple Answer | Wildfire Solution
counting-words-simple-answer-wildfire-so-4b7r
IntuitionThe problem requires counting how many words in a list start with a specific prefix. The simplest approach is to iterate through the list of words and
22A31A05A9
NORMAL
2025-01-09T17:16:27.504965+00:00
2025-01-09T17:16:27.504965+00:00
10
false
# Intuition The problem requires counting how many words in a list start with a specific prefix. The simplest approach is to iterate through the list of words and check if each word begins with the prefix. This can be efficiently done using the startswith() method provided by Python. # Approach Initialize a counter variable (count) to zero. Loop through the list of words: For each word, use the startswith() method to check if it begins with the given prefix. If the condition is true, increment the counter by one. Once all words have been checked, return the value of the counter as the result. # Complexity - Time complexity: O(n⋅m) n: Number of words in the list. m: Average length of the words or the prefix length (whichever is smaller). The startswith() method performs a character-by-character comparison for up to the prefix length - Space complexity: O(1) The approach uses constant space since no additional data structures are created, apart from a few variables for counting and iteration. # Code ```python [] class Solution(object): def prefixCount(self, words, pref): """ :type words: List[str] :type pref: str :rtype: int """ count = 0 for i in words: if i.startswith(pref): count += 1 return count ```
2
0
['Python']
1
counting-words-with-a-given-prefix
0 ms | Beats 100% | Easy to Understand | Counting Words With a Given Prefix
0-ms-beats-100-easy-to-understand-counti-ttvl
IntuitionWhen solving the problem, the key idea is to identify words in the array that start with the given prefix. A prefix means the beginning part of a word
aash24
NORMAL
2025-01-09T17:04:43.151959+00:00
2025-01-09T17:04:43.151959+00:00
16
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> When solving the problem, the key idea is to identify words in the array that start with the given prefix. A prefix means the beginning part of a word must match exactly with the given string, and we only need to check the first characters up to the length of the prefix for each word. The problem is straightforward if we focus on directly comparing the prefix with the initial part of each word. # Approach <!-- Describe your approach to solving the problem. --> 1. Iterate Through the Array: - Loop through each word in the words array. 2. Check Prefix Match: - For each word, compare its first len characters (where len is the length of pref) with the prefix string pref. This can be done using a substring comparison function like strncmp in C. 3. Count Matches: - If the prefix matches, increment a counter. 4. Return the Count: - After traversing all words in the array, return the count of matches. 5. Return the Count # Complexity - Time complexity: O(n⋅m), where: - n is the number of words in the words array. - m is the average length of words and the length of the prefix. - This is because comparing the prefix with the initial part of each word takes O(m) time for each of the n words. <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) (constant space). - No extra data structures are used. <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```c [] int prefixCount(char** words, int wordsSize, char* pref) { int len = strlen(pref); int count = 0; for(int i = 0; i < wordsSize; i++){ if(strncmp(words[i], pref, len) == 0){ count ++; } } return count; } ```
2
0
['Array', 'String', 'C', 'String Matching']
0
counting-words-with-a-given-prefix
✅Beats 100% | C++ | Simple & Easy to Understand 💥
beats-100-c-simple-easy-to-understand-by-wqq6
Intuition💡My first thought on how to solve this problem was to iterate through each word in the words vector and check if it starts with the given prefix pref.
krishpravkorimilli
NORMAL
2025-01-09T17:00:35.291967+00:00
2025-01-09T17:00:35.291967+00:00
8
false
# Intuition💡 <!-- Describe your first thoughts on how to solve this problem. --> My first thought on how to solve this problem was to iterate through each word in the words vector and check if it starts with the given prefix pref. I knew that the find method in C++ could be used to check if a string contains a substring, and I suspected that it could also be used to check if a string starts with a certain prefix. # Approach🚀 <!-- Describe your approach to solving the problem. --> My approach to solving this problem was to use a simple iterative approach. Here are the steps: Initialize a counter variable count to 0. 📊 Iterate through each word in the words vector. 🔁 For each word, use the find method to check if the word starts with the given prefix pref. 🔍 If the word starts with the prefix (i.e., find returns 0), increment the count variable. 👍 Finally, return the total count of words that start with the given prefix. 📈 # Complexity🤔 - Time complexity:⏰ <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n⋅m), where n is the number of words and m is the maximum length of a word. - Space complexity:📦 <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1), as we only use a constant amount of space to store the count variable. # Code ```cpp [] class Solution { public: int prefixCount(vector<string>& words, string pref) { int count = 0; for (const auto& word : words) { if (word.find(pref) == 0) { count++; } } return count; } }; ```
2
0
['C++']
0
counting-words-with-a-given-prefix
EASY JAVA CODE
easy-java-code-by-ayeshakhan7-akcj
IntuitionApproach UsingUsing TrieComplexity Time complexity: O(n^l + m), where n = number of words, m = length of pref, l = average length of word Space comple
ayeshakhan7
NORMAL
2025-01-09T16:32:12.446279+00:00
2025-01-09T16:32:12.446279+00:00
9
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach Using <!-- Describe your approach to solving the problem. --> Using Trie # Complexity - Time complexity: O(n^l + m), where n = number of words, m = length of pref, l = average length of word <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n^l) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class TrieNode { TrieNode[] children; boolean isEndOfWord; int count; TrieNode() { children = new TrieNode[26]; isEndOfWord = false; count = 0; } } class Trie { TrieNode root; Trie() { root = new TrieNode(); } void insert(String word) { TrieNode pCrawl = root; for(char ch : word.toCharArray()) { int idx = ch - 'a'; if(pCrawl.children[idx] == null) { pCrawl.children[idx] = new TrieNode(); } pCrawl = pCrawl.children[idx]; pCrawl.count++; } pCrawl.isEndOfWord = true; } int searchPrefixCount(String pref) { TrieNode pCrawl = root; for(char ch : pref.toCharArray()) { int idx = ch - 'a'; if(pCrawl.children[idx] == null) { return 0; } pCrawl = pCrawl.children[idx]; } return pCrawl.count; } } class Solution { public int prefixCount(String[] words, String pref) { Trie trie = new Trie(); for(String word : words) { trie.insert(word); } return trie.searchPrefixCount(pref); } } ```
2
0
['Java']
0