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
sender-with-largest-word-count
Easy to understand!
easy-to-understand-by-shrikanta8-vqu7
```\nclass Solution {\npublic:\n \n int func(string s){\n int c=0;\n for(auto n: s){\n if(n==\' \') c++;\n }\n retu
Shrikanta8
NORMAL
2022-05-28T16:21:39.361988+00:00
2022-05-28T16:21:39.362024+00:00
66
false
```\nclass Solution {\npublic:\n \n int func(string s){\n int c=0;\n for(auto n: s){\n if(n==\' \') c++;\n }\n return c+1;\n }\n string largestWordCount(vector<string>& m, vector<string>& senders) {\n map<string,int> mp;\n for(int i=0;i<m.size(); i++){\n mp[senders[i]] += func(m[i]);\n }\n int maxVal = INT_MIN;\n string ans="";\n \n for(auto it:mp){\n if(it.second >= maxVal){\n maxVal = it.second;\n ans = it.first;\n }\n \n }\n return ans;\n\n }\n};
2
0
['C']
1
sender-with-largest-word-count
String Stream and hashmap || C++
string-stream-and-hashmap-c-by-neerajsat-w6i7
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> hm;\n in
NeerajSati
NORMAL
2022-05-28T16:03:08.528009+00:00
2022-05-28T16:03:08.528033+00:00
126
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> hm;\n int n = messages.size();\n for(int i=0;i<n;i++){\n istringstream ss(messages[i]);\n string temp;\n int cnt = 0;\n while(getline(ss,temp,\' \')){\n cnt++;\n }\n hm[senders[i]] += cnt;\n }\n int mx = INT_MIN;\n for(auto it:hm){\n mx = max(it.second,mx);\n }\n string ans="";\n for(auto it:hm){\n if(mx == it.second){\n if(ans < it.first){\n ans = it.first;\n }\n }\n }\n return ans;\n }\n};\n```
2
0
['C']
1
sender-with-largest-word-count
C++ || EASY TO UNDERSTAND || Simple Approach
c-easy-to-understand-simple-approach-by-8cvgo
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n int n=m.size();\n map<string,vector<string>> mp
aarindey
NORMAL
2022-05-28T16:02:20.942953+00:00
2022-05-28T16:02:20.942983+00:00
53
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n int n=m.size();\n map<string,vector<string>> mp;\n int maxi=-1;\n string ans="asdja";\n for(int i=0;i<n;i++)\n {\n string str=m[i]+\' \';\n int left=0;\n for(int j=0;j<str.size();j++)\n {\n if(str[j]==\' \')\n {\n string str2=str.substr(left,j-left);\n \n left=j+1;\n mp[s[i]].push_back(str2);\n maxi=max((int)maxi,(int)mp[s[i]].size());\n }\n }\n }\n for(auto pr:mp)\n {\n if(pr.second.size()==maxi)\n {\n ans=pr.first;\n }\n }\n return ans;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome**
2
0
[]
0
sender-with-largest-word-count
C++ | StringStream
c-stringstream-by-vaibhavshekhawat-xzjy
``` \nstring largestWordCount(vector& m, vector& s) {\n string ans;\n int Maxcnt=0;\n unordered_map umap;\n\n for(int i=0;i>word){
vaibhavshekhawat
NORMAL
2022-05-28T16:00:59.574437+00:00
2022-05-28T16:00:59.574476+00:00
187
false
``` \nstring largestWordCount(vector<string>& m, vector<string>& s) {\n string ans;\n int Maxcnt=0;\n unordered_map<string,int> umap;\n\n for(int i=0;i<s.size();i++){\n stringstream ss(m[i]);\n string word;\n int cnt=0;\n while(ss>>word){\n cnt++;\n }\n int k=cnt;\n cnt+=umap[s[i]]; // taking previous counts\n if(cnt>Maxcnt){\n ans=s[i];\n Maxcnt=cnt;\n }\n else if(Maxcnt==cnt){\n if(s[i]>ans) ans=s[i];\n }\n umap[s[i]]+=k;\n }\n return ans;\n }\n
2
0
['C']
0
sender-with-largest-word-count
SIMPLE TO UNDERSTAND
simple-to-understand-by-dummy_nick-y7u4
IntuitionApproachComplexity Time complexity: Space complexity: Code
Dummy_Nick
NORMAL
2025-03-23T13:21:34.912832+00:00
2025-03-23T13:21:34.912832+00:00
15
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 String largestWordCount(String[] messages, String[] senders) { int n = senders.length; Map<String, Integer> user = new HashMap<>(); for(int i=0; i<n; i++) { String sender = senders[i]; int count = messages[i].split(" ").length; user.put(sender,user.getOrDefault(sender,0)+count); } String maxUser = ""; int max = 0; for(Map.Entry<String,Integer> map : user.entrySet()) { String sender = map.getKey(); int count = map.getValue(); if(count > max || (count==max && sender.compareTo(maxUser) > 0)) { max = count; maxUser = sender; } } return maxUser; } } ```
1
0
['Java']
2
sender-with-largest-word-count
Easy Solution Heap C++
easy-solution-heap-c-by-saadbro-rg72
\n# Code\n\nclass Solution {\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n ios::sync_with_stdio(false);\n cin.ti
Saadbro
NORMAL
2024-02-27T15:09:21.040569+00:00
2024-02-27T15:09:21.040601+00:00
31
false
\n# Code\n```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n ios::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n\n unordered_map <string, int> mp;\n int i, j;\n for(i = 0; i < s.size(); i++)\n {\n int cnt = 0;\n for(j = 0; j < m[i].size(); j++)\n {\n if(m[i][j] == \' \')\n cnt++;\n }\n mp[s[i]] += cnt + 1;\n }\n\n auto cmp = [&](string &a, string &b){\n if(mp[a] == mp[b])\n {\n return a < b;\n }\n return mp[a] < mp[b];\n };\n\n priority_queue <string, vector <string>, decltype(cmp)> pq(cmp);\n for(auto x : mp)\n pq.push(x.first);\n return pq.top();\n }\n};\n```
1
0
['Hash Table', 'Heap (Priority Queue)', 'C++']
0
sender-with-largest-word-count
Easy Solution || Map+Priority_Queue(Heap) || C++
easy-solution-mappriority_queueheap-c-by-g8at
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
AMIT5446TIWARI
NORMAL
2023-12-01T09:40:30.029216+00:00
2023-12-01T09:40:30.029237+00:00
16
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 string largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n=messages.size();\n unordered_map<string,int>mp;\n for(int i=0;i<n;i++){\n int count=1;\n for(int j=0;j<messages[i].size();j++){\n if(messages[i][j]==\' \') count++;\n }\n mp[senders[i]]+=count;\n }\n priority_queue<pair<int,string>>pq;\n for(auto it:mp){\n pq.push({it.second,it.first});\n }\n return pq.top().second;\n }\n};\n```
1
0
['Ordered Map', 'Heap (Priority Queue)', 'C++']
0
sender-with-largest-word-count
Sender With Largest Word Count
sender-with-largest-word-count-by-riya12-6f6t
\n\n# Code\n\nclass Solution {\n static class sArranger implements Comparable<sArranger>{\n String name;\n int count;\n int index;\n
riya1202
NORMAL
2023-10-24T10:09:16.659680+00:00
2023-10-24T10:09:16.659712+00:00
378
false
\n\n# Code\n```\nclass Solution {\n static class sArranger implements Comparable<sArranger>{\n String name;\n int count;\n int index;\n sArranger(String s,int c,int i){\n name=s;\n count=c;\n index=i;\n }\n public int compareTo(sArranger s){\n if(this.count==s.count){\n return s.name.compareTo(this.name);\n }\n return s.count-this.count;\n }\n }\n public String largestWordCount(String[] messages, String[] senders) {\n TreeMap<String,Integer> mp=new TreeMap<>();\n int maxIndex=0;\n for(int i=0;i<messages.length;i++){\n int count=messages[i].split(" ").length;\n if(mp.containsKey(senders[i]))\n mp.put(senders[i],mp.get(senders[i])+count);\n else\n mp.put(senders[i],count);\n }\n PriorityQueue<sArranger> pq=new PriorityQueue<>();\n Set<String> keys = mp.keySet();\n\n for(String s:keys){\n pq.add(new sArranger(s,mp.get(s),0));\n }\n return pq.remove().name;\n }\n}\n```
1
0
['Array', 'Hash Table', 'String', 'Counting', 'Java']
0
sender-with-largest-word-count
✅Simple Cpp Solution using Hashmap🔥
simple-cpp-solution-using-hashmap-by-usc-jmh9
Intuition\nCount of total number of words in a string will equal to the count of spaces plus one.\n\n# Approach\n- At first we will create a map storing the sen
uscutkarsh
NORMAL
2023-10-05T12:21:46.549676+00:00
2023-10-05T12:21:46.549704+00:00
39
false
# Intuition\nCount of total number of words in a string will equal to the count of spaces plus one.\n\n# Approach\n- At first we will create a map storing the sender with their word count.\n- Then we will parse the map to find the sender with the maximum word-count.\n\n# Complexity\n- Time complexity:\nO(n) - Double pass Solution\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string, int> m;\n\n for(int i = 0; i < senders.size(); i++){\n int wordCount = count(messages[i].begin(), messages[i].end(), \' \') + 1;\n cout << wordCount << endl;\n m[senders[i]] += wordCount; \n }\n\n string ans = "";\n int count = 0;\n for(auto it : m){\n if(it.second >= count){\n count = it.second;\n ans = it.first;\n }\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
0
sender-with-largest-word-count
easy c++ solution || using map and stl
easy-c-solution-using-map-and-stl-by-rhy-gy5e
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
Rhythm_1383
NORMAL
2023-08-25T08:59:40.014737+00:00
2023-08-25T08:59:40.014756+00:00
449
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 string largestWordCount(vector<string>& m, vector<string>& s) {\n unordered_map<string,int> mp;\n int mx=INT_MIN;\n string ans="";\n for(int i=0;i<m.size();i++)\n {\n char ch=\' \';\n int counter=0;\n counter=count(m[i].begin(),m[i].end(),ch);\n mp[s[i]]+=(counter+1);\n if(mp[s[i]] == mx){\n ans = max(ans ,s[i] );\n }\n else if(mp[s[i]] > mx){\n mx = mp[s[i]];\n ans = s[i];\n }\n } \n return ans;\n }\n};\n```
1
0
['C++']
0
sender-with-largest-word-count
Java Easy to Understand Solution with explanation
java-easy-to-understand-solution-with-ex-vpg4
Code\n\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> ans = new TreeMap<>(); // Usin
brothercode
NORMAL
2023-07-23T09:00:52.485445+00:00
2023-07-23T09:01:04.623698+00:00
6
false
# Code\n```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> ans = new TreeMap<>(); // Using treemap for its Default Natural Sorting Order to tackle Lexicography.\n\t\tList<String> res = new ArrayList<>(); \n\t\tint n = messages.length;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tif (ans.containsKey(senders[i])) {\n\t\t\t\tint sum = ans.get(senders[i]) + messages[i].split(" ").length; // When the sender is already present add the subsequent message word lengths to current word length.\n\t\t\t\tans.put(senders[i], sum);\n\t\t\t} else\n\t\t\t\tans.put(senders[i], messages[i].split(" ").length);\n\t\t}\n\t\tint max = 0;\n\t\tfor (int i : ans.values()) {\n\t\t\tif (max < i)\n\t\t\t\tmax = i; // Find the longest message value. \n\t\t}\n\t\tfor (String s : ans.keySet()) {\n\t\t\tif (ans.get(s) == max)\n\t\t\t\tres.add(s); // Take all the Lexicographically ordered string in a list without disturbing the order.\n\t\t}\n\t\treturn res.get(res.size() - 1); // Always the last string would be the Lexicographically longest.\n }\n}\n```\n\nPlease upvote if you like this solution. Thanks.
1
0
['Java']
0
sender-with-largest-word-count
EASY || SIMPLE || BASIC
easy-simple-basic-by-arya_ratan-s5pm
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
arya_ratan
NORMAL
2023-05-25T17:33:22.086734+00:00
2023-05-25T17:33:22.086775+00:00
398
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\n int helper(string &s){\n int ans = 0;\n int i=0;\n while(i < s.length()){\n while(i < s.length() && s[i] != \' \'){\n i++;\n }\n i++;\n ans++;\n }\n return ans;\n }\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string, int> mp;\n string ans = "";\n int mx = 0;\n\n for(int i=0;i<messages.size();i++){\n int count = helper(messages[i]);\n mp[senders[i]] += count;\n if(mp[senders[i]] == mx){\n ans = max(ans ,senders[i] );\n }\n else if(mp[senders[i]] > mx){\n mx = mp[senders[i]];\n ans = senders[i];\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
0
sender-with-largest-word-count
Easy Solution using Counting
easy-solution-using-counting-by-vaibhavk-ffnp
Intuition\n Describe your first thoughts on how to solve this problem. \ncounting and hashmap\n# Approach\n Describe your approach to solving the problem. \ncou
vaibhavk01
NORMAL
2023-05-04T18:05:36.681327+00:00
2023-05-04T18:05:36.681369+00:00
287
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncounting and hashmap\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncount each senders word and store in hashmap. If current count is more than max_count, then update the sender\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n int max_count = INT_MIN, cnt, n=senders.size(); \n map<string, int> mp;\n\n string msg, sender, ms="";\n \n for (int i=0; i<n; i++) {\n msg = messages[i], sender = senders[i];\n \n mp[sender] += count(msg.begin(), msg.end(), \' \')+1;\n \n cnt = mp[sender];\n \n if (cnt > max_count) {\n max_count = cnt;\n ms = sender;\n }\n else if (cnt == max_count) {\n if (sender > ms) ms = sender;\n }\n \n }\n\n return ms;\n }\n};\n```
1
0
['Counting', 'C++']
1
sender-with-largest-word-count
Most intuitive Python Solution
most-intuitive-python-solution-by-racern-y2ll
\nfrom collections import defaultdict\n\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n \n d =
Racerninja
NORMAL
2022-12-04T16:41:03.847529+00:00
2022-12-04T16:41:03.847567+00:00
18
false
```\nfrom collections import defaultdict\n\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n \n d = defaultdict(int)\n ans = [0, \'a\']\n \n for i, x in enumerate(messages):\n d[senders[i]] += x.count(\' \') + 1\n ans = max(ans, [d[senders[i]], senders[i]])\n \n return ans[1]\n```
1
0
['Python']
0
sender-with-largest-word-count
C++ || Intuitive || HashMap
c-intuitive-hashmap-by-the_marvelous_one-7ltq
\n\nclass Solution {\npublic:\n string largestWordCount(vector& messages, vector& senders) {\n \n string ans="";\n map mp;\n for(
the_marvelous_one
NORMAL
2022-11-19T05:29:59.434099+00:00
2022-11-19T05:29:59.434137+00:00
455
false
```\n\n```class Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n \n string ans="";\n map<string, int> mp;\n for(int i=0; i<messages.size(); i++)\n {\n string s = messages[i];\n for(int j=0; j<s.size(); j++){\n if(s[j] == \' \')\n mp[senders[i]]+=1;\n }\n mp[senders[i]]+=1;\n }\n \n int maxi = INT_MIN;\n for(auto i: mp){\n if(i.second >= maxi){\n maxi=i.second;\n if(i.first>ans)\n ans=i.first;\n }\n }\n return ans;\n }\n};
1
0
['C']
0
sender-with-largest-word-count
c++ | easy | short
c-easy-short-by-nehagupta_09-ejnn
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n {\n unordered_map<string,int>mp;\n
NehaGupta_09
NORMAL
2022-10-29T07:40:07.800640+00:00
2022-10-29T07:40:07.800680+00:00
479
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n {\n unordered_map<string,int>mp;\n int size = messages.size();\n int words=0;\n int val=0;\n string ans="";\n string str;\n for(int i=0;i<size;i++)\n {\n str = messages[i];\n words=0;\n for(int j=0;j<str.length();j++)\n {\n if(str[j]==\' \')\n {\n words++;\n }\n }\n words++;\n mp[senders[i]]+=words;\n if(val<mp[senders[i]])\n {\n val=mp[senders[i]];\n ans=senders[i];\n }\n else if(val==mp[senders[i]] and senders[i]>ans)\n {\n ans=senders[i];\n }\n }\n return ans;\n }\n};\n```
1
0
['C', 'C++']
0
sender-with-largest-word-count
easy cpp solution count method
easy-cpp-solution-count-method-by-akshat-mj6r
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n {\n string name="";\n int ans=IN
akshat0610
NORMAL
2022-10-29T07:39:54.541995+00:00
2022-10-29T07:39:54.542029+00:00
343
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n {\n string name="";\n int ans=INT_MIN;\n unordered_map<string,int>mp;\n for(int i=0;i<messages.size();i++)\n {\n int val = count(messages[i].begin(),messages[i].end(),\' \')+1;\n mp[senders[i]]+=val;\n if(mp[senders[i]]>ans or (mp[senders[i]]==ans and senders[i]>name))\n {\n ans=mp[senders[i]];\n name=senders[i];\n }\n }\n return name;\n }\n};\n```
1
0
['C', 'C++']
0
sender-with-largest-word-count
c++ | easy | short
c-easy-short-by-akshat0610-knc0
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n{\n unordered_map<string,int>mp;\n int size
akshat0610
NORMAL
2022-10-29T07:25:25.271468+00:00
2022-10-29T07:25:25.271508+00:00
284
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) \n{\n unordered_map<string,int>mp;\n int size = messages.size();\n \n for(int i=0;i<size;i++)\n {\n \tstring str = messages[i];\n \t\n \tint idx=0;\n \t\n \twhile(idx<str.length())\n \t{\n string s="";\n \t\twhile(idx<str.length() and ((str[idx]>=\'a\' and str[idx]<=\'z\') or (str[idx]>=\'A\' and str[idx]<=\'Z\')))\n \t\t{\n \t\t\t s.push_back(str[idx]);\n \t\t\t idx++;\n\t\t\t}\n\t\t\tmp[senders[i]]=mp[senders[i]]+1;\n\t\t\twhile(idx<str.length() and (str[idx]==\' \'))\n\t\t\t{\n\t\t\t\tidx++;\n\t\t\t}\n\t\t}\n\t}\n\tint val = INT_MIN;\n\tfor(auto it=mp.begin();it!=mp.end();it++)\n\t{\n\t\tif(it->second > val)\n\t\t{\n\t\t\tval = it->second;\n\t\t}\n\t}\n\tstring ans="";\n\tfor(auto it=mp.begin();it!=mp.end();it++)\n\t{\n\t\tif(it->second == val and it->first > ans)\n\t\t{\n\t\t\tans=it->first;\n\t\t}\n\t}\n\treturn ans;\n}\n};\n```
1
0
['C', 'C++']
0
sender-with-largest-word-count
c++ | easy | short
c-easy-short-by-venomhighs7-ym4o
\n\n# Code\n\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders){\n map<string, int> mp;\n f
venomhighs7
NORMAL
2022-10-26T00:17:59.584063+00:00
2022-10-26T00:17:59.584088+00:00
210
false
\n\n# Code\n```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders){\n map<string, int> mp;\n for(int i = 0; i<messages.size(); ++i){\n int words = count(begin(messages[i]), end(messages[i]), \' \')+1;\n mp[senders[i]]+=words;\n }\n string ans = "";\n int count = 0;\n for(auto it = mp.begin(); it!=mp.end(); ++it){\n if(it->second >= count){\n count = it->second;\n ans = it->first;\n }\n }\n return ans;\n }\n\n};\n```
1
0
['C++']
0
sender-with-largest-word-count
Similar approach to "Top k Frequent Words"
similar-approach-to-top-k-frequent-words-4uct
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
Kshitij_Pandey
NORMAL
2022-10-19T16:48:56.692132+00:00
2022-10-19T16:48:56.692179+00:00
7
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 String largestWordCount(String[] messages, String[] senders) {\n int n = senders.length;\n int[] count = new int[n];\n\n for(int i=0; i< n; i++){\n String currmessage = messages[i];\n String[] arr = currmessage.split(" ");\n int val = arr.length;\n count[i] = val;\n }\n HashMap<String, Integer> map = new HashMap<>();\n for(int i=0; i< n; i++){\n map.put(senders[i], map.getOrDefault(senders[i], 0) + count[i]);\n }\n PriorityQueue<String> maxHeap = new PriorityQueue<>(\n (a,b) ->{\n //if length is same sort according to name \n if(map.get(a).equals(map.get(b))){\n return b.compareTo(a);\n }\n //else according to count of words\n else{\n return map.get(b) - map.get(a);\n }\n }\n );\n\n for(String s: map.keySet()){\n maxHeap.offer(s);\n }\n return maxHeap.poll();\n }\n}\n```
1
0
['Java']
0
sender-with-largest-word-count
Python O(n)
python-on-by-hong_zhao-jk8z
python\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n count = defaultdict(int)\n largest, nam
hong_zhao
NORMAL
2022-10-19T03:19:04.000727+00:00
2022-10-19T03:20:09.510043+00:00
131
false
```python\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n count = defaultdict(int)\n largest, name = 0, \'\'\n for i in range(len(messages)):\n count[senders[i]] += messages[i].count(\' \') + 1\n if count[senders[i]] > largest \\\n or (count[senders[i]] == largest and senders[i] > name):\n largest = count[senders[i]]\n name = senders[i]\n return name\n```
1
0
['Python']
1
sender-with-largest-word-count
C++ | Map | Vector of Pairs | Sorting | Easy Understanding |
c-map-vector-of-pairs-sorting-easy-under-kyf0
```\nclass Solution {\npublic:\n string largestWordCount(vector& m, vector& s) {\n \n unordered_mapmpp;\n \n for(int i=0;i<m.size();++i)
mr_kamran
NORMAL
2022-09-28T09:21:06.241284+00:00
2022-09-28T09:21:06.241323+00:00
155
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n \n unordered_map<string,int>mpp;\n \n for(int i=0;i<m.size();++i)\n {\n int cnt=0;\n for(int j=0;j<m[i].size();++j)\n {\n if(m[i][j]==\' \') cnt++;\n \n }\n mpp[s[i]]+=cnt+1;\n \n }\n \n vector<pair<int,string>>vp;\n \n for(auto it:mpp)\n {\n vp.push_back(make_pair(it.second,it.first));\n \n }\n \n sort(vp.begin(),vp.end());\n \n return vp[vp.size()-1].second ;\n }\n};
1
0
['C++']
0
sender-with-largest-word-count
BruteForce to Optimal Solution 🔥 | Explained 💯 [C++]
bruteforce-to-optimal-solution-explained-ds0e
1. Brute Force Solution [Accepted \u2705]\n### Approach ->\nwe have taken a HashMap to store the count of words (in a message, counted using stringstream) of ea
dcoder_op
NORMAL
2022-08-07T13:14:41.659392+00:00
2022-08-07T13:14:41.659435+00:00
25
false
## 1. Brute Force Solution [Accepted \u2705]\n### Approach ->\nwe have taken a **HashMap** to store the **count of words** (*in a message, counted using `stringstream`*) of each sender.\n\nand as we were inserting values, **we kept track of max frequency** at that point of time using `mx = max(mx, freq[senders[i]]);`\n\nAt last, just do **deal with equal frequencies**, we created a `set<string>` to get sender names in **Lexicogrphically Sorted Order** (Last string in the set will be Lexicographically largest).\n\n\n\n```\nstring largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n = senders.size();\n\n unordered_map<string, int> freq;\n int mx = INT_MIN;\n\n for(int i = 0; i < n; ++i) {\n int cnt = 0;\n\n stringstream ss(messages[i]);\n string word;\n\n while(ss >> word)\n ++cnt;\n\n freq[senders[i]] += cnt;\n mx = max(mx, freq[senders[i]]);\n }\n\n\n set<string> st;\n\n for(auto &it : freq)\n if(it.second == mx)\n st.insert(it.first);\n\n return *st.rbegin();\n}\n```\n## 2. Optimised [Accepted \u2705]\n### Approach ->\nwe are doing kind of similar things here too, but in an **Optimised Way!** \uD83D\uDD25\n\nwe are storing the count of words (in a message, *counted using white spaces* `\' \'`) of each sender and at the same time **Comparing the max frequency** and as well as **strings** (in case of *same frequency*, to find **Lexicographically Largest**)\n```\nstring largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n = senders.size();\n string maxString = "";\n int maxMsgs = 0;\n\n unordered_map<string, int> count;\n\n for(int i = 0; i < n; ++i) {\n int words = 1; // total spaces + 1\n string msg = messages[i];\n string sender = senders[i];\n\n for(const char &c : msg)\n if(c == \' \')\n ++words;\n\n count[sender] += words;\n\n if((count[sender] > maxMsgs)|| (count[sender] == maxMsgs && sender > maxString)) {\n maxString = sender;\n maxMsgs = count[sender];\n }\n }\n\n return maxString;\n}\n```\n\nI Hope you found it **Helpful** \uD83D\uDCA1 , and if you have *Any Doubts*, **Please ask in Comments** \uD83D\uDCAC\n### Kindly UpVote \uD83D\uDD3C, it Really Motivates :) \uD83D\uDD25
1
1
['String', 'C', 'C++']
0
sender-with-largest-word-count
C++ easy solution
c-easy-solution-by-anish-debug10-n6hc
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> mpp;\n s
anish-debug10
NORMAL
2022-07-07T13:59:48.097371+00:00
2022-07-07T13:59:48.097416+00:00
32
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> mpp;\n string temp="";\n int j;\n for(int i=0;i<senders.size();i++)\n {\n for(j=0;j<messages[i].size();j++)\n {\n if(messages[i][j]==\' \')\n mpp[senders[i]]++;\n }\n if(j==messages[i].size())\n mpp[senders[i]]++;\n }\n \n int maxfreq=INT_MIN;\n for(auto it:mpp)\n {\n if(maxfreq < it.second)\n {\n maxfreq=it.second;\n temp=it.first;\n }\n }\n \n for(auto it:mpp)\n {\n if(it.second==maxfreq && temp < it.first)\n {\n temp=it.first;\n }\n }\n return temp;\n }\n};\n```
1
0
[]
0
sender-with-largest-word-count
Python solution
python-solution-by-dhanu084-g3g3
```\ndef largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n hashmap = defaultdict(int)\n \n for i in range(len(messa
dhanu084
NORMAL
2022-07-06T06:19:32.755314+00:00
2022-07-06T06:19:32.755360+00:00
42
false
```\ndef largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n hashmap = defaultdict(int)\n \n for i in range(len(messages)):\n hashmap[senders[i]] += len(messages[i].split(" "))\n \n\t\t# (hashmap.get(x),x) -> sort by frequency of words used or if frequency is same sort by the sender name\n result = sorted(hashmap.keys(), key=lambda x: (hashmap.get(x), x), reverse = True)\n \n return result[0]
1
0
['Sorting']
0
sender-with-largest-word-count
Easy with map
easy-with-map-by-tuanbieber-pwta
\nfunc largestWordCount(messages []string, senders []string) string {\n m := make(map[string]int)\n \n for i := 0; i < len(senders); i++ {\n m[s
tuanbieber
NORMAL
2022-06-28T10:51:40.751729+00:00
2022-06-28T10:51:40.751775+00:00
209
false
```\nfunc largestWordCount(messages []string, senders []string) string {\n m := make(map[string]int)\n \n for i := 0; i < len(senders); i++ {\n m[senders[i]] += len(strings.Split(messages[i], " "))\n }\n\n maxSender := senders[0]\n maxMessage := m[maxSender]\n \n for key, value := range m {\n if value > maxMessage || (value == maxMessage && key > maxSender) {\n maxSender = key\n maxMessage = value\n }\n }\n \n return maxSender\n}\n```
1
0
['C', 'Python', 'Java', 'Go', 'JavaScript']
2
sender-with-largest-word-count
C++ || HashMap with comparison
c-hashmap-with-comparison-by-eren_vish-l47s
The code is self explanatory\n\n```\nclass Solution {\npublic: \n \n static bool cmp(pair& a, pair& b) // always remember in a class the sort function n
Eren_Vish
NORMAL
2022-06-23T17:01:10.953360+00:00
2022-06-23T17:01:10.953402+00:00
26
false
The code is self explanatory\n\n```\nclass Solution {\npublic: \n \n static bool cmp(pair<int,string>& a, pair<int,string>& b) // always remember in a class the sort function needs static function.\n {\n if(a.first == b.first) return a.second > b.second;\n return a.first > b.first;\n }\n \n string largestWordCount(vector<string>& m, vector<string>& s) {\n vector<pair<int,string>> v;\n unordered_map<string,int> mp; // use map to cover the cases of multiple msg on same name.\n \n for(int i = 0; i < s.size(); i++)\n {\n int c= 0;\n for(int j = 0; j < m[i].size(); j++)\n {\n if(m[i][j] == \' \') c++; \n }\n \n mp[s[i]] += c+1;\n }\n \n for(auto k : mp) v.push_back({k.second, k.first});\n sort(v.begin(), v.end(), cmp);\n \n return v[0].second; \n \n \n }\n};
1
0
['C']
0
sender-with-largest-word-count
JavaScript | One Liner 🔥😎☝️
javascript-one-liner-by-gpambasana-o87j
\n/**\n * @param {string[]} messages\n * @param {string[]} senders\n * @return {string}\n */\nconst largestWordCount = (messages, senders) => Object.entries(sen
gpambasana
NORMAL
2022-06-22T12:36:22.078080+00:00
2022-06-22T12:37:47.034555+00:00
83
false
```\n/**\n * @param {string[]} messages\n * @param {string[]} senders\n * @return {string}\n */\nconst largestWordCount = (messages, senders) => Object.entries(senders.reduce((counter, name, i) => (counter[name] = (counter[name] ?? 0) + messages[i].split(/\\s/).length, counter), {})).sort((a, b) => b[1] - a[1] !== 0 ? b[1] - a[1] : (a[0] > b[0] ? -1 : 1))[0][0];\n```
1
0
['JavaScript']
2
sender-with-largest-word-count
C++ using hashmap
c-using-hashmap-by-vibhanshu2001-6h3c
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> mp;\n in
vibhanshu2001
NORMAL
2022-06-20T17:01:48.663915+00:00
2022-06-20T17:01:48.663956+00:00
27
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> mp;\n int ans=INT_MIN;\n string temp="-1";\n for(int i=0;i<messages.size();i++){\n int count=0;\n stringstream sss(messages[i]);\n string word;\n while(sss>>word){\n count++;\n }\n mp[senders[i]] += count;\n }\n for(auto it:mp)\n {\n if(it.second>ans)\n {\n ans=it.second;\n temp=it.first;\n }\n else if(it.second==ans)\n {\n temp=max(temp,it.first);\n }\n }\n return temp;\n }\n};\n```
1
0
[]
1
sender-with-largest-word-count
Unique and Easy Python Solution | Unique approach | Memory usage less than 99.91%
unique-and-easy-python-solution-unique-a-3fcy
\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n \n dic = {}\n name = 0\n while
Abhi-Jit
NORMAL
2022-06-11T20:15:34.973716+00:00
2022-06-11T20:19:10.412499+00:00
39
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n \n dic = {}\n name = 0\n while senders:\n print(senders[name] , messages[name].lstrip().rstrip())\n \n if senders[name] not in dic:\n dic[senders[name]] = len(messages[name].lstrip().rstrip().split(\' \'))\n\n else:\n dic[senders[name]] += len(messages[name].lstrip().rstrip().split(\' \'))\n \n senders.pop(name)\n messages.pop(name)\n \n \n d = {}\n for key , val in dic.items():\n if val not in d:\n d[val] = [key]\n \n else:\n d[val].append(key)\n \n d[val].sort(reverse = True)\n \n \n return d[max(d)][0]\n```
1
0
['Python']
0
sender-with-largest-word-count
Rust, HashMap counter, split(' '), O(n)
rust-hashmap-counter-split-on-by-goodgoo-vdrh
\nuse std::collections::HashMap;\nimpl Solution {\n pub fn largest_word_count(messages: Vec<String>, senders: Vec<String>) -> String {\n let n = sende
goodgoodwish
NORMAL
2022-06-02T03:30:33.676568+00:00
2022-06-02T03:30:33.676600+00:00
68
false
```\nuse std::collections::HashMap;\nimpl Solution {\n pub fn largest_word_count(messages: Vec<String>, senders: Vec<String>) -> String {\n let n = senders.len();\n let mut xs = HashMap::new();\n let mut hi = 0;\n let mut ans = String::new();\n for (i, x) in senders.into_iter().enumerate() {\n let cnt = messages[i].split(" ").collect::<Vec<&str>>().len();\n *xs.entry(x.clone()).or_insert(0) += cnt;\n if xs[&x] > hi || (xs[&x] == hi && x > ans) {\n hi = xs[&x];\n ans = x;\n }\n }\n ans\n }\n}\n```
1
0
['Rust']
0
sender-with-largest-word-count
js solution using map
js-solution-using-map-by-radowan-irw3
\nvar largestWordCount = function(messages, senders) {\n let map = new Map();\n for(let i=0;i<messages.length;i++){\n if(map.get(senders[i])){\n
Radowan
NORMAL
2022-05-30T18:03:28.852789+00:00
2022-05-30T18:03:28.852833+00:00
29
false
```\nvar largestWordCount = function(messages, senders) {\n let map = new Map();\n for(let i=0;i<messages.length;i++){\n if(map.get(senders[i])){\n map.set(senders[i],map.get(senders[i])+messages[i].split(\' \').length); \n }\n else map.set(senders[i],messages[i].split(\' \').length);\n }\n let max=0,ans=\'\';\n for(let [key,val] of map){\n if(val>max){\n max=val;\n ans=key\n }else if(val===max){\n ans = key>ans ? key: ans;\n }\n }\n return ans;\n};\n```
1
0
['JavaScript']
0
sender-with-largest-word-count
Simple Java Solution in O(n).
simple-java-solution-in-on-by-vishrutgot-yl0e
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n ArrayList<String> key=new ArrayList();\n HashMap<S
vishrutgoti
NORMAL
2022-05-30T17:46:46.992926+00:00
2022-05-30T17:46:46.992966+00:00
45
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n ArrayList<String> key=new ArrayList();\n HashMap<String, Integer> mp=new HashMap();\n int max = Integer.MIN_VALUE;\n for(int i=0;i<messages.length;i++){\n int temp = messages[i].split(" ").length;\n if(mp.containsKey(senders[i])){\n mp.put(senders[i], mp.get(senders[i])+temp);\n }\n else{\n mp.put(senders[i],temp);\n key.add(senders[i]);\n }\n max = Math.max(max, mp.get(senders[i]));\n }\n Collections.sort(key);\n for(int i=key.size()-1;i>=0;i--){\n if(mp.get(key.get(i))==max)return key.get(i);\n }\n return "";\n }\n}\n```
1
0
[]
0
sender-with-largest-word-count
Python | 4 lines (clean and precise)
python-4-lines-clean-and-precise-by-ma5t-pa4p
Code:\n\n\n\t\td1={}\n for i in range(len(messages)): d1[senders[i]]=d1.get(senders[i],0)+(len(messages[i].split(\' \')))\n t=sorted(d1.items(),ke
ma5termiind
NORMAL
2022-05-29T06:02:23.464319+00:00
2022-05-29T06:02:23.464364+00:00
34
false
Code:\n\n```\n\t\td1={}\n for i in range(len(messages)): d1[senders[i]]=d1.get(senders[i],0)+(len(messages[i].split(\' \')))\n t=sorted(d1.items(),key= lambda x: (-x[1],x[0]))\n for i in range(len(t)-1,-1,-1):\n if t[i][1]==t[0][1]: return t[i][0]\n```
1
0
['String', 'Sorting']
2
sender-with-largest-word-count
cpp best and easy sollution using MAP
cpp-best-and-easy-sollution-using-map-by-6mux
class Solution {\npublic:\n string largestWordCount(vector& messages, vector& senders) {\n int n=senders.size();\n unordered_map mp;\n \
Adityabillore
NORMAL
2022-05-29T05:27:53.799168+00:00
2022-05-29T05:27:53.799208+00:00
13
false
class Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n=senders.size();\n unordered_map<string,int> mp;\n \n for(int i=0;i<n;i++){\n mp[senders[i]]++;\n int size=messages[i].length();\n for(int j=0;j<size;j++){\n if(messages[i][j]==\' \')\n mp[senders[i]]++;\n }\n }\n int count=0;\n string ans="";\n for(auto x : mp){\n if(count<x.second){\n count=x.second;\n ans=x.first;\n }\n if(count==x.second and x.first>ans)\n ans=x.first;\n }\n return ans;\n }\n};
1
0
[]
0
sender-with-largest-word-count
C++ | | Easy solution | | (Map and set)
c-easy-solution-map-and-set-by-harsh_neg-ikg1
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> m1;\n int maxi = 0
negiharsh12
NORMAL
2022-05-29T00:30:07.263966+00:00
2022-05-29T00:31:08.851560+00:00
52
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> m1;\n int maxi = 0;\n\t\t\n for(int i=0;i<senders.size();i++){\n\t\t\t// min. no. of words per sender\n int req = 1;\n\t\t\t\n\t\t\t// count spaces\n for(auto &it:messages[i]) if(it==\' \') req++;\n \n\t\t\t// insert it into map\n\t\t\tm1[senders[i]] += req;\n\t\t\t\n\t\t\t// get the max value in map\n maxi = max(maxi,m1[senders[i]]);\n }\n\t\t// using set for highest order string\n\t\tset<string> s1;\n\t\t\n for(auto &it:m1){\n\t\t\n // string correponding to max value of map\n\t\t\tif(it.second==maxi){\n s1.insert(it.first);\n }\n }\n\t\t\n\t\t// last element of set\n return *(--s1.end());\n }\n};\n```
1
0
['C']
1
sender-with-largest-word-count
java easy solution using hashmap
java-easy-solution-using-hashmap-by-rake-x1us
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n HashMap<String,Integer> map=new HashMap();\n Strin
Rakesh_Sharma_4
NORMAL
2022-05-28T20:40:55.449158+00:00
2022-05-28T20:40:55.449195+00:00
69
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n HashMap<String,Integer> map=new HashMap();\n String name=senders[0];\n int max=Integer.MIN_VALUE;\n for(int i=0;i<senders.length;i++)\n {\n String[] arr=messages[i].split(" ");\n map.put(senders[i],map.getOrDefault(senders[i],0)+arr.length);\n if(max==map.get(senders[i]) && senders[i].compareTo(name)>=0)\n {\n name=senders[i];\n }\n else if(max<map.get(senders[i]))\n {\n max=map.get(senders[i]);\n name=senders[i];\n }\n }\n return name;\n \n }\n}\n```
1
0
['Java']
0
sender-with-largest-word-count
Python O(n) space and O(n) time
python-on-space-and-on-time-by-loganyu-wrxo
\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n count_by_sender = Counter()\n max_messages =
loganyu
NORMAL
2022-05-28T18:16:40.044258+00:00
2022-05-28T18:16:40.044299+00:00
24
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n count_by_sender = Counter()\n max_messages = 0\n for message, sender in zip(messages, senders):\n word_count = len(message.split(" "))\n count_by_sender[sender] += word_count\n max_messages = max(max_messages, count_by_sender[sender])\n \n max_sender = None\n for sender in senders:\n if count_by_sender[sender] == max_messages and (not max_sender or sender > max_sender):\n max_sender = sender\n \n return max_sender\n```
1
0
[]
0
sender-with-largest-word-count
Faster || Easy To Understand || C++ Code
faster-easy-to-understand-c-code-by-__kr-z1tu
Time Complexity : O(N * size of string)\n\n Space Complexity : O(N)*\n\n\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vecto
__KR_SHANU_IITG
NORMAL
2022-05-28T17:50:25.631149+00:00
2022-05-28T17:50:25.631193+00:00
26
false
* ***Time Complexity : O(N * size of string)***\n\n* ***Space Complexity : O(N)***\n\n```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n \n int n = messages.size();\n \n unordered_map<string, int> mp;\n \n for(int i = 0; i < n; i++)\n {\n string str = messages[i];\n \n string name = senders[i];\n \n int count = 0;\n \n for(int j = 0; j < str.size(); j++)\n {\n if(str[j] == \' \')\n {\n count++;\n }\n }\n \n mp[name] += count + 1;\n }\n \n int maxi = 0;\n \n string max_name = "";\n \n for(auto x : mp)\n {\n if(x.second > maxi)\n {\n maxi = x.second;\n \n max_name = x.first;\n }\n else if(x.second == maxi)\n {\n if(max_name < x.first)\n {\n max_name = x.first;\n }\n }\n }\n \n return max_name;\n }\n};\n```
1
0
['C']
0
sender-with-largest-word-count
Python Solution
python-solution-by-user6397p-u07z
\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d = defaultdict(list)\n \n for m, s in
user6397p
NORMAL
2022-05-28T17:14:59.476095+00:00
2022-05-28T17:14:59.476142+00:00
65
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d = defaultdict(list)\n \n for m, s in zip(messages, senders):\n d[s].append(m)\n\n longest = [0, []]\n for s in d:\n l = 0\n for m in d[s]:\n l += len(m.split())\n if l > longest[0]:\n longest[0] = l\n longest[1] = [s]\n elif l == longest[0]:\n longest[1].append(s)\n \n return max(longest[1])\n```
1
0
['Python3']
0
sender-with-largest-word-count
Python3 | 5 Lines | Easy understanding
python3-5-lines-easy-understanding-by-yz-va87
\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d = defaultdict(int)\n for sender, size in zi
yzhao156
NORMAL
2022-05-28T16:58:40.584180+00:00
2022-05-28T16:58:40.584210+00:00
41
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n d = defaultdict(int)\n for sender, size in zip( senders, [len(message.split()) for message in messages] ):\n d[sender] += size\n max_word = max(d.values())\n return sorted([sender for sender, size in d.items() if size == max_word])[-1]\n```
1
0
['Python3']
0
sender-with-largest-word-count
Count Spaces
count-spaces-by-guptasim8-53i5
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> sent;\n int i=0;\n
guptasim8
NORMAL
2022-05-28T16:21:35.831385+00:00
2022-05-28T16:21:35.831407+00:00
34
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> sent;\n int i=0;\n for(string msg:messages){\n int state = 1;\n int wc = 0;\n for (char c:msg)\n {\n if (c == \' \' ) state = 1;\n else if (state)\n {\n state = 0;\n ++wc;\n }\n }\n sent[senders[i]]+=wc;\n i++;\n }\n int max=-1;\n string ans="";\n for(auto p:sent){\n //word with max count\n if(max< p.second){\n max=p.second;\n ans=p.first;\n }\n else if(max== p.second){\n\t\t\t//lexographically largest name\n if(ans<p.first)\n ans=p.first;\n }\n }\n return ans;\n }\n};\n```
1
0
['String']
0
sender-with-largest-word-count
Python || 7-Liner || 100% Solution || simple & fast
python-7-liner-100-solution-simple-fast-bbr2b
python\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n conversation=dict()\n for message, send
hyeseon
NORMAL
2022-05-28T16:21:03.809733+00:00
2022-05-28T16:21:03.809761+00:00
37
false
```python\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n conversation=dict()\n for message, sender in zip(messages, senders):\n if sender not in conversation:\n conversation[sender]=0\n conversation[sender]+=len(message.split(" "))\n sorted_conversation = sorted(conversation.items(), key=lambda x: (x[1], x[0]), reverse=True)\n return sorted_conversation[0][0]\n```\n\nPlease commnet below if you have any further questions and **UPVOTE** if you like it!\nAll the solutions that I\'ve been through is archived here: https://github.com/hyeseonko/LeetCode
1
0
['Python']
0
sender-with-largest-word-count
Smooth af || explanation in comments with Clean Code || C++
smooth-af-explanation-in-comments-with-c-bizz
\nclass Solution {\nprivate:\n \n int solve(string &s) //this function is to count the number of spaces\n {\n s += \' \';\n int cnt =0;\n
binayKr
NORMAL
2022-05-28T16:13:59.399693+00:00
2022-05-28T16:13:59.399733+00:00
33
false
```\nclass Solution {\nprivate:\n \n int solve(string &s) //this function is to count the number of spaces\n {\n s += \' \';\n int cnt =0;\n for(int i=0; i<s.length(); i++)\n {\n if(s[i]==\' \') cnt++;\n }\n return cnt;\n }\n \npublic:\n \n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> mp;\n for(int i=0; i<messages.size(); i++)\n {\n int words = solve(messages[i]);\n mp[senders[i]]+= words;\n }\n \n string ans;\n int max_words = -1;\n for(auto &it : mp)\n {\n if(it.second == max_words)\n {\n char temp = it.first[0];\n ans = (ans[0]>temp) ? ans : it.first; //this will return the lexicographically greater string!!\n }\n \n else if(it.second > max_words)\n {\n ans = it.first;\n max_words = it.second;\n }\n }\n return ans;\n }\n};\n```\n
1
0
['String']
0
sender-with-largest-word-count
TreeMap | Java Solution
treemap-java-solution-by-_mahimasingh-44ri
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n // retains the String order. Hence, we can find the lexic
_mahimasingh_
NORMAL
2022-05-28T16:12:31.629098+00:00
2022-05-28T16:13:52.399992+00:00
53
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n // retains the String order. Hence, we can find the lexicographically largest name if more than one sender with the largest word count \n TreeMap<String, Integer> map= new TreeMap<>();\n \n for(int i=0;i<messages.length;i++)\n {\n int c= countWords(messages[i]);\n map.put(senders[i],map.getOrDefault(senders[i],0)+c);\n }\n int max=0;\n String ans="";\n for(String k: map.keySet())\n {\n\t\t\t//>= since we need to find the lexicographically largest\n if(map.get(k)>=max)\n {\n max=map.get(k);\n ans=k;\n }\n }\n return ans;\n }\n public int countWords(String str)\n {\n\n if (str == null || str.isEmpty())\n return 0;\n String[] words = str.split("\\\\s+");\n return words.length;\n }\n}\n```
1
0
['Tree', 'Java']
0
sender-with-largest-word-count
Python very short and simple
python-very-short-and-simple-by-gauau-h0da
\ndef largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n\tdic = defaultdict(int)\n\tfor s, m in zip(senders, messages):\n\t\tdic[s] += m.
gauau
NORMAL
2022-05-28T16:07:56.403112+00:00
2022-05-28T16:09:31.726293+00:00
64
false
```\ndef largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n\tdic = defaultdict(int)\n\tfor s, m in zip(senders, messages):\n\t\tdic[s] += m.count(\' \') + 1\n\treturn max([(c, s) for s, c in dic.items()])[1]\n```
1
0
[]
1
sender-with-largest-word-count
Hash map | Ordered map | Easy to understand
hash-map-ordered-map-easy-to-understand-as7bx
\nclass Solution {\npublic:\n void helper(string s,int &cnt)\n {\n for(int i=0;i<s.length();i++)\n {\n if(s[i]==\' \')\n
itzyash_01
NORMAL
2022-05-28T16:07:00.435170+00:00
2022-05-28T16:07:00.435215+00:00
73
false
```\nclass Solution {\npublic:\n void helper(string s,int &cnt)\n {\n for(int i=0;i<s.length();i++)\n {\n if(s[i]==\' \')\n cnt++;\n }\n if(s!="") cnt++;\n }\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n map<string,int> mp;\n for(int i=0;i<messages.size();i++)\n {\n string s=senders[i];\n int cnt=0;\n helper(messages[i],cnt);\n mp[s]=mp[s]+cnt;\n }\n int x=0;\n string ans="";\n for(auto ele: mp)\n {\n if(x<=ele.second)\n {\n x=ele.second;\n ans=ele.first;\n }\n }\n return ans;\n }\n};\n```
1
0
['String', 'C']
0
sender-with-largest-word-count
Solution in Python | Hashmap | Sorting
solution-in-python-hashmap-sorting-by-re-k5f9
\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n leng = len(senders)\n freq = {}\n for
rebirthing
NORMAL
2022-05-28T16:06:50.150817+00:00
2022-05-28T16:06:50.150866+00:00
165
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n leng = len(senders)\n freq = {}\n for i in range(leng):\n sender = senders[i]\n msg = messages[i]\n msg_len = len(msg.split())\n if sender in freq:\n freq[sender] += msg_len\n else:\n freq[sender] = msg_len\n \n \n max_sender_len = float(\'-inf\')\n max_sender_name = \'\'\n \n for sender in freq:\n if freq[sender] > max_sender_len:\n max_sender_len = freq[sender]\n max_sender_name = sender\n elif freq[sender] == max_sender_len:\n temp = sorted([sender, max_sender_name], key=str, reverse=True)\n max_sender_name = temp[0]\n \n return max_sender_name\n```
1
0
['Sorting', 'Python', 'Python3']
1
sender-with-largest-word-count
Leetcode 2284 Simple O(Nlog N)->TC ,O(N)- >SC solution
leetcode-2284-simple-onlog-n-tc-on-sc-so-4u2y
\'\'\'\nclass Solution {\npublic:\n int count(string &s)\n { \n //if string is empty ,there are no words\n if(s.size()==0)\n re
akashkinkarpandey
NORMAL
2022-05-28T16:06:44.387210+00:00
2022-05-28T16:07:04.526897+00:00
17
false
\'\'\'\nclass Solution {\npublic:\n int count(string &s)\n { \n //if string is empty ,there are no words\n if(s.size()==0)\n return 0;\n int n=s.size();\n //counter to count words\n int c=0;\n for(int i=0;i<n;i++)\n {\n if(s[i]==\' \')\n c++;\n }\n //count of number of words is one more than count of spaces\n return (c+1);\n }\n string largestWordCount(vector<string>& msg, vector<string>& s) \n {\n int n=msg.size();\n //since we count frequency of words by sender\n //we use long long to avoid overflow while counting\n unordered_map<string,long long>m;\n for(int i=0;i<n;i++)\n {\n\t\t//we add 0LL to avoid overflow in integer by doing calculation in long long\n m[s[i]]=m[s[i]]+0ll+count(msg[i]);\n }\n //we first find maximum frequency of words by any sender\n long long maxi=0;\n for(auto &i:m)\n {\n if((i.second+0ll)>maxi)\n maxi=i.second;\n }\n //Then we find all senders with same maximum frequency and store them in vector\n vector<string>ans;\n for(auto &i:m)\n {\n if(i.second==maxi)\n {\n cout<<i.first<<" "<<i.second<<endl;\n ans.push_back(i.first);\n }\n }\n //we sort the answer vector to get lexicographically largest vector at end\n sort(ans.begin(),ans.end());\n return ans[ans.size()-1];\n }\n};\n\'\'\'
1
0
['Sorting']
0
sender-with-largest-word-count
TreeMap | Java Solution
treemap-java-solution-by-me_tanmay-io64
java\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> map = new TreeMap<>();\n
me_tanmay
NORMAL
2022-05-28T16:05:58.534352+00:00
2022-05-28T16:05:58.534386+00:00
46
false
```java\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> map = new TreeMap<>();\n for (int i = 0; i < messages.length; i++) {\n String s = messages[i];\n String[] str = s.split(" ");\n map.put(senders[i], map.getOrDefault(senders[i], 0) + str.length);\n }\n String ans = "";\n int max = 0;\n for (String key : map.keySet()) {\n if (map.get(key) >= max) {\n max = map.get(key);\n ans = key.compareTo(ans) >= 0 ? key : ans;\n }\n }\n return ans;\n }\n}\n```
1
0
['String', 'Tree', 'Java']
0
sender-with-largest-word-count
c++ || solution
c-solution-by-soujash_mandal-76cj
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& msg, vector<string>& s) {\n map<string,int> m;\n set<string> st;\n
soujash_mandal
NORMAL
2022-05-28T16:04:13.404189+00:00
2022-05-28T16:04:13.404225+00:00
46
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& msg, vector<string>& s) {\n map<string,int> m;\n set<string> st;\n \n int n=s.size();\n \n for(int i=0;i<n;i++)\n {\n st.insert(s[i]);\n int n1=msg[i].size();\n int count=1;\n for(int j=0;j<n1;j++)\n {\n if(msg[i][j]==\' \') count++;\n }\n m[s[i]]+=count;\n }\n \n vector<string> v(st.begin(),st.end());\n \n reverse(v.begin(),v.end());\n \n n=v.size();\n \n string res=v[0];\n int count=m[v[0]];\n \n for(int i=0;i<n;i++)\n {\n if(m[v[i]]>count)\n {\n res=v[i];\n count=m[v[i]];\n }\n }\n \n return res;\n }\n};\n```
1
0
[]
0
sender-with-largest-word-count
Python Easy Solution using Hashing and Sorting
python-easy-solution-using-hashing-and-s-4q2n
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n mapping, res = {}, []\n \n for i, s
mikueen
NORMAL
2022-05-28T16:04:12.295162+00:00
2022-05-28T16:06:27.873729+00:00
75
false
```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n mapping, res = {}, []\n \n for i, sender in enumerate(senders):\n if sender not in mapping:\n mapping[sender] = len(messages[i].split())\n else:\n mapping[sender] += len(messages[i].split())\n \n mapping = {val[0] : val[1] for val in sorted(mapping.items(), key = lambda x: (-x[1], x[0]))}\n max_val = max(mapping.values())\n \n for k, v in mapping.items():\n if v == max_val:\n res.append(k)\n \n if len(res) == 1:\n return res[0]\n \n res.sort(key = len)\n res.sort(key = str)\n \n return res[-1]
1
0
['Sorting', 'Python', 'Python3']
0
sender-with-largest-word-count
C++ || no use of StringStream
c-no-use-of-stringstream-by-panacotta-lvng
\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n = messages.size();\n unorder
panacotta
NORMAL
2022-05-28T16:04:05.435895+00:00
2022-05-28T16:04:27.534862+00:00
77
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n int n = messages.size();\n unordered_map<string,int> mp; // count of words for each sender.\n \n int count = 0;\n for(int i = 0;i<n;i++){\n count = 0;\n string s = messages[i];\n for(int j = 0;j<s.size();j++){\n if(s[j] == \' \'){\n count++;\n }\n }\n count++;\n mp[senders[i]]+= count;\n }\n vector<int> counts; // for all the counts, made extra array for (if in the case) more than one \n // maximums.\n for(auto &it : mp){\n counts.push_back(it.second);\n }\n int ctmax = *max_element(counts.begin(),counts.end()); \n vector<string> ans;\n for(auto &it : mp){\n if(it.second == ctmax)\n ans.push_back(it.first);\n }\n // populated ans with all the maximums.\n if(ans.size() == 1)\n return ans[0];\n else{\n return *max_element(ans.begin(),ans.end());\n }\n }\n};\n```
1
0
['C']
2
sender-with-largest-word-count
Simple C++ without StringStream
simple-c-without-stringstream-by-mohit_m-z3jl
```\nclass Solution {\npublic:\n string largestWordCount(vector& messages, vector& senders) {\n unordered_map maps;\n int n = messages.size();\
mohit_motwani
NORMAL
2022-05-28T16:03:46.108928+00:00
2022-05-28T16:03:46.108974+00:00
31
false
```\nclass Solution {\npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n unordered_map<string,int> maps;\n int n = messages.size();\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < messages[i].length(); j++) {\n if(messages[i][j] == \' \')\n maps[senders[i]]++;\n }\n maps[senders[i]]++;\n }\n int maxFqr = INT_MIN;\n string ans = "";\n for(auto x : maps) {\n // cout<<x.first<<" "<<x.second<<endl;\n if(x.second > maxFqr) {\n maxFqr = x.second;\n ans = x.first;\n }\n else if(x.second == maxFqr) {\n if(ans.compare(x.first) < 0)\n ans = x.first;\n }\n }\n return ans;\n \n }\n};
1
0
['C', 'C++']
0
sender-with-largest-word-count
Python Easy Approach
python-easy-approach-by-constantine786-ixtd
The pseudo code is as follows:\n1. Find the word count tally for each sender. \n2. Find the max word count.\n3. Find lexicographically larger sender name if the
constantine786
NORMAL
2022-05-28T16:03:32.075281+00:00
2022-05-28T16:16:51.347522+00:00
129
false
The pseudo code is as follows:\n1. Find the word count tally for each sender. \n2. Find the max word count.\n3. Find lexicographically larger sender name if there are more than one senders with same max word count.\n\nMy implementation is as follows:\n```\nclass Solution:\n def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n counter = defaultdict(int)\n max_count = -math.inf\n res=\'\'\n # find the word count tally for each sender\n for message, sender in zip(messages, senders): \n counter[sender]+=len(message.split(\' \'))\n \n if counter[sender]>=max_count:\n # pick lexicographically larger name in case same word count\n if max_count<counter[sender] or sender>res: \n res=sender\n max_count=counter[sender] \n \n return res \n```\n**Time - O(n)**\n**Space - O(n)** - space to store the `counter` dict\n\n---\n\n***Please upvote if you find it useful***
1
0
['Python', 'Python3']
0
sender-with-largest-word-count
simple efficient solution
simple-efficient-solution-by-maverick09-p2ku
\nclass Solution {\n#define ln ListNode\n#define tn TreeNode\n#define endl \'\\n\'\n typedef long long ll;\n typedef vector<ll> vi;\n const ll mod = 1e
maverick09
NORMAL
2022-05-28T16:03:27.248154+00:00
2022-05-28T16:03:27.248190+00:00
48
false
```\nclass Solution {\n#define ln ListNode\n#define tn TreeNode\n#define endl \'\\n\'\n typedef long long ll;\n typedef vector<ll> vi;\n const ll mod = 1e9;\npublic:\n string largestWordCount(vector<string>& m, vector<string>& s) {\n ll sz = m.size();\n unordered_map<string, ll>ump;\n for (ll i = 0;i < sz;++i) {\n string& snd = s[i];\n ll cnt = 1;\n for (char& ch : m[i])\n if (ch == \' \')\n cnt++;\n ump[snd] += cnt;\n }\n string snd="";\n for (auto& it : ump) {\n if (snd.empty() || it.second > ump[snd] || (it.second == ump[snd] && it.first > snd))\n snd = it.first;\n }\n return snd;\n }\n};\n```
1
0
[]
0
sender-with-largest-word-count
Java, O(N)
java-on-by-asd92-a5tn
Please upvote if helpful.\n\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n // Count the words for every s
asd92
NORMAL
2022-05-28T16:01:42.880260+00:00
2022-05-28T16:01:42.880285+00:00
57
false
Please upvote if helpful.\n```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n // Count the words for every sender and return the sender with the maximum words.\n // Time: O(N), Space: O(N)\n Map<String, Integer> map = new HashMap();\n String ans = "";\n for (int i = 0; i < senders.length; i++) {\n if (!map.containsKey(senders[i])) map.put(senders[i], 0);\n int max = ans == "" ? 0 : map.get(ans);\n map.put(senders[i], map.get(senders[i]) + messages[i].split(" ").length);\n if (map.get(senders[i]) >= max) {\n if (map.get(senders[i]) == max) {\n ans = senders[i].compareTo(ans) < 0 ? ans : senders[i];\n } else {\n ans = senders[i];\n }\n }\n }\n return ans;\n }\n}\n```
1
0
[]
0
sender-with-largest-word-count
[JAVA] Short and Sweet
java-short-and-sweet-by-aayushgarg-rjbc
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> hm = new HashMap<>();\n for(i
aayushgarg
NORMAL
2022-05-28T16:01:41.625841+00:00
2022-05-29T12:59:07.075582+00:00
60
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> hm = new HashMap<>();\n for(int i=0; i<senders.length; i++){\n int len = messages[i].split("\\\\s+").length;\n hm.put(senders[i], hm.getOrDefault(senders[i],0) + len);\n }\n \n List<String> al = new ArrayList<>(hm.keySet()); \n Collections.sort(al, (a, b) -> (hm.get(b) == hm.get(a)) ? b.compareTo(a) : (hm.get(b) - hm.get(a)));\n \n return al.get(0);\n }\n}\n```\nTC: O(nlogn) SC: O(N)
1
0
[]
2
sender-with-largest-word-count
Java Solution with HashMap
java-solution-with-hashmap-by-solved-1izg
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> map = new HashMap<>();\n \n
solved
NORMAL
2022-05-28T16:01:35.412033+00:00
2022-05-28T16:01:35.412070+00:00
69
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String, Integer> map = new HashMap<>();\n \n for (int i = 0; i < messages.length; i++) {\n String message = messages[i];\n String[] words = message.split(" ");\n map.put(senders[i], map.getOrDefault(senders[i], 0) + words.length);\n }\n \n int maxValue = Integer.MIN_VALUE;\n String result = "";\n \n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n String key = entry.getKey();\n int value = entry.getValue();\n if (value > maxValue) {\n maxValue = value;\n result = key;\n continue;\n }\n if (value == maxValue && key.compareTo(result) > 0) {\n result = key;\n continue;\n }\n }\n return result;\n }\n}\n```
1
1
['Java']
0
sender-with-largest-word-count
Clean Java Priority Queue Solution
clean-java-priority-queue-solution-by-ph-jfaa
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n HashMap<String, Integer> map = new HashMap<>();\n
phatkararnav
NORMAL
2022-05-28T16:01:14.673863+00:00
2022-05-28T16:10:13.344646+00:00
90
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n HashMap<String, Integer> map = new HashMap<>();\n int max = 0;\n for(int i = 0; i < senders.length; i++) {\n int size = messages[i].split(" ").length;\n map.put(senders[i], map.getOrDefault(senders[i], 0) + size);\n max = Math.max(max, map.get(senders[i]));\n }\n \n PriorityQueue<String> pq = new PriorityQueue<>(Collections.reverseOrder());\n for(String key : map.keySet()) {\n if(map.get(key) == max) {\n pq.add(key);\n }\n }\n return pq.poll();\n }\n}\n```
1
0
[]
0
sender-with-largest-word-count
Java Treemap
java-treemap-by-siddu6003-pra5
\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String,Integer> m=new TreeMap<>();\n int n=mes
siddu6003
NORMAL
2022-05-28T16:00:56.489475+00:00
2022-05-28T16:01:51.574228+00:00
117
false
```\nclass Solution {\n public String largestWordCount(String[] messages, String[] senders) {\n Map<String,Integer> m=new TreeMap<>();\n int n=messages.length;\n for(int i=0;i<n;i++){\n String a[]=messages[i].split(" ");\n if(m.containsKey(senders[i])){\n m.put(senders[i],m.get(senders[i])+a.length);\n }else{\n m.put(senders[i],a.length);\n }\n }\n \n int max=Collections.max(m.values());\n String ans="";\n for(Map.Entry k : m.entrySet()){\n int x= (int)k.getValue();\n if(x==max){\n ans=String.valueOf(k.getKey());\n }\n }\n return ans;\n }\n}\n\n```
1
0
['Java']
1
sender-with-largest-word-count
⚡ Easy Approach | Hash Map and Priority Queue
easy-approach-hash-map-and-priority-queu-10uj
cpp\nclass Solution {\n \npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n\n int n = messages.size();\n
abanoub7asaad
NORMAL
2022-05-28T16:00:42.205904+00:00
2022-05-28T16:01:08.368015+00:00
113
false
```cpp\nclass Solution {\n \npublic:\n string largestWordCount(vector<string>& messages, vector<string>& senders) {\n\n int n = messages.size();\n unordered_map<string, int> mp; //name, cnt\n priority_queue<pair<int, string>> pq; //cnt, name\n \n for(int i = 0; i < n; i++) {\n int cnt = 1;\n for(auto j : messages[i]) {\n if(j == \' \')\n cnt++;\n }\n mp[senders[i]] += cnt;\n pq.push({mp[senders[i]], senders[i]});\n }\n \n return pq.top().second;\n }\n};\n```
1
0
['C', 'Heap (Priority Queue)']
0
word-search
Accepted very short Java solution. No additional space.
accepted-very-short-java-solution-no-add-s2q5
Here accepted solution based on recursion. To save memory I decuded to apply bit mask for every visited cell. Please check board[y][x] ^= 256;\n\n public boo
pavel-shlyk
NORMAL
2015-01-25T17:11:41+00:00
2019-05-18T05:46:31.899866+00:00
266,217
false
Here accepted solution based on recursion. To save memory I decuded to apply bit mask for every visited cell. Please check board[y][x] ^= 256;\n\n public boolean exist(char[][] board, String word) {\n char[] w = word.toCharArray();\n for (int y=0; y<board.length; y++) {\n \tfor (int x=0; x<board[y].length; x++) {\n \t\tif (exist(board, y, x, w, 0)) return true;\n \t}\n }\n return false;\n }\n\t\n\tprivate boolean exist(char[][] board, int y, int x, char[] word, int i) {\n\t\tif (i == word.length) return true;\n\t\tif (y<0 || x<0 || y == board.length || x == board[y].length) return false;\n\t\tif (board[y][x] != word[i]) return false;\n\t\tboard[y][x] ^= 256;\n\t\tboolean exist = exist(board, y, x+1, word, i+1)\n\t\t\t|| exist(board, y, x-1, word, i+1)\n\t\t\t|| exist(board, y+1, x, word, i+1)\n\t\t\t|| exist(board, y-1, x, word, i+1);\n\t\tboard[y][x] ^= 256;\n\t\treturn exist;\n\t}
732
42
[]
166
word-search
Python dfs solution with comments.
python-dfs-solution-with-comments-by-old-jq5w
\n def exist(self, board, word):\n if not board:\n return False\n for i in xrange(len(board)):\n for j in xrange(len(
oldcodingfarmer
NORMAL
2015-08-28T20:39:34+00:00
2018-10-14T06:28:58.597633+00:00
143,234
false
\n def exist(self, board, word):\n if not board:\n return False\n for i in xrange(len(board)):\n for j in xrange(len(board[0])):\n if self.dfs(board, i, j, word):\n return True\n return False\n \n # check whether can find word, start at (i,j) position \n def dfs(self, board, i, j, word):\n if len(word) == 0: # all the characters are checked\n return True\n if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:\n return False\n tmp = board[i][j] # first character is found, check the remaining part\n board[i][j] = "#" # avoid visit agian \n # check whether can find "word" along one direction\n res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \\\n or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])\n board[i][j] = tmp\n return res
545
7
['Depth-First Search', 'Python']
60
word-search
✅96.45%🔥Easy Solution🔥with explanation🔥
9645easy-solutionwith-explanation-by-mra-injv
Intuition\n#### The problem can be solved by traversing the grid and performing a depth-first search (DFS) for each possible starting position. At each cell, we
MrAke
NORMAL
2024-04-03T00:14:54.779930+00:00
2024-04-03T00:14:54.779953+00:00
95,580
false
# Intuition\n#### The problem can be solved by traversing the grid and performing a depth-first search (DFS) for each possible starting position. At each cell, we check if the current character matches the corresponding character of the word. If it does, we explore all four directions (up, down, left, right) recursively until we find the complete word or exhaust all possibilities.\n---\n\n# Approach\n#### 1. Implement a recursive function `backtrack` that takes the current position `(i, j)` in the grid and the current index `k` of the word.\n#### 2.Base cases:\n - ##### If `k` equals the length of the word, return `True`, indicating that the word has been found.\n - ##### If the current position `(i, j)` is out of the grid boundaries or the character at `(i, j)` does not match the character at index `k` of the word, return `False`.\n#### 3.Mark the current cell as visited by changing its value or marking it as empty.\n#### 4. Recursively explore all four directions (up, down, left, right) by calling `backtrack` with updated positions `(i+1, j), (i-1, j), (i, j+1), and (i, j-1)`.\n#### 5.If any recursive call returns `True`, indicating that the word has been found, return `True`.\n#### 6. If none of the recursive calls returns `True`, reset the current cell to its original value and return `False`.\n#### 7. Iterate through all cells in the grid and call the `backtrack` function for each cell. If any call returns `True`, return `True`, indicating that the word exists in the grid. Otherwise, return `False`.\n\n---\n\n# Complexity\n- ## Time complexity:\n#### $$O(m * n * 4^l)$$, where m and n are the dimensions of the grid and l is the length of the word. The $$4^l$$ factor represents the maximum number of recursive calls we may have to make for each starting cell.\n\n- ## Space complexity:\n#### $$O(l)$$, where l is the length of the word. The space complexity is primarily due to the recursive stack depth during the DFS traversal.\n\n---\n# Code\n\n```python []\nclass Solution:\n def exist(self, board, word):\n def backtrack(i, j, k):\n if k == len(word):\n return True\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[k]:\n return False\n \n temp = board[i][j]\n board[i][j] = \'\'\n \n if backtrack(i+1, j, k+1) or backtrack(i-1, j, k+1) or backtrack(i, j+1, k+1) or backtrack(i, j-1, k+1):\n return True\n \n board[i][j] = temp\n return False\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if backtrack(i, j, 0):\n return True\n return False\n```\n```C++ []\nclass Solution {\npublic:\n bool exist(vector<vector<char>>& board, string word) {\n int m = board.size();\n int n = board[0].size();\n \n function<bool(int, int, int)> backtrack = [&](int i, int j, int k) {\n if (k == word.length()) {\n return true;\n }\n if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[k]) {\n return false;\n }\n \n char temp = board[i][j];\n board[i][j] = \'\\0\';\n \n if (backtrack(i + 1, j, k + 1) || backtrack(i - 1, j, k + 1) || \n backtrack(i, j + 1, k + 1) || backtrack(i, j - 1, k + 1)) {\n return true;\n }\n \n board[i][j] = temp; \n return false;\n };\n \n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (backtrack(i, j, 0)) {\n return true;\n }\n }\n }\n return false;\n }\n};\n\n```\n```java []\npublic class Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length;\n int n = board[0].length;\n\n boolean[][] visited = new boolean[m][n];\n boolean result = false;\n \n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (board[i][j] == word.charAt(0)) {\n result = backtrack(board, word, visited, i, j, 0);\n if (result) return true;\n }\n }\n }\n \n return false;\n }\n \n private boolean backtrack(char[][] board, String word, boolean[][] visited, int i, int j, int index) {\n if (index == word.length()) {\n return true;\n }\n \n if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || visited[i][j] || board[i][j] != word.charAt(index)) {\n return false;\n }\n \n visited[i][j] = true;\n \n if (backtrack(board, word, visited, i + 1, j, index + 1) ||\n backtrack(board, word, visited, i - 1, j, index + 1) ||\n backtrack(board, word, visited, i, j + 1, index + 1) ||\n backtrack(board, word, visited, i, j - 1, index + 1)) {\n return true;\n }\n \n visited[i][j] = false;\n return false;\n }\n}\n\n```\n```javascript []\nvar exist = function(board, word) {\n const m = board.length;\n const n = board[0].length;\n \n const backtrack = (i, j, k) => {\n if (k === word.length) {\n return true;\n }\n if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] !== word.charAt(k)) {\n return false;\n }\n \n const temp = board[i][j];\n board[i][j] = \'\\0\'; \n \n const result = backtrack(i + 1, j, k + 1) || \n backtrack(i - 1, j, k + 1) || \n backtrack(i, j + 1, k + 1) || \n backtrack(i, j - 1, k + 1);\n \n board[i][j] = temp; \n return result;\n };\n \n for (let i = 0; i < m; ++i) {\n for (let j = 0; j < n; ++j) {\n if (backtrack(i, j, 0)) {\n return true;\n }\n }\n }\n return false;\n};\n\n```\n```C# []\npublic class Solution {\n public bool Exist(char[][] board, string word) {\n int m = board.Length;\n int n = board[0].Length;\n \n Func<int, int, int, bool> backtrack = null;\n backtrack = (i, j, k) => {\n if (k == word.Length) {\n return true;\n }\n if (i < 0 || i >= m || j < 0 || j >= n || board[i][j] != word[k]) {\n return false;\n }\n \n char temp = board[i][j];\n board[i][j] = \'\\0\';\n bool result = backtrack(i + 1, j, k + 1) || \n backtrack(i - 1, j, k + 1) || \n backtrack(i, j + 1, k + 1) || \n backtrack(i, j - 1, k + 1);\n \n board[i][j] = temp; \n return result;\n };\n \n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (backtrack(i, j, 0)) {\n return true;\n }\n }\n }\n return false;\n }\n}\n\n```\n---\n\n\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/aff812e9-9751-4e8c-be5f-636ebb5e4fa4_1712103254.8384917.png)\n\n\n\n
490
3
['Array', 'String', 'Backtracking', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']
25
word-search
Solution
solution-by-deleted_user-62cr
C++ []\nclass Solution {\npublic:\n bool isExist = false;\n void backtrack(string &word, string &solution, int row, int col, int const rowSize, int const
deleted_user
NORMAL
2023-02-09T13:23:40.929367+00:00
2023-03-09T10:02:37.031806+00:00
55,011
false
```C++ []\nclass Solution {\npublic:\n bool isExist = false;\n void backtrack(string &word, string &solution, int row, int col, int const rowSize, int const colSize, vector<vector<char>> &board,vector<vector<int>> &visited){\n if(solution.back() != word.at(solution.size()-1) || visited.at(row).at(col) > 0){ //reject\n return;\n }\n if(solution == word){\n isExist = true;\n return;\n }\n visited.at(row).at(col)++;\n vector<int> DIR = {0, 1, 0, -1, 0};\n for(int i = 0; i < 4; i++){\n int new_row = row + DIR[i];\n int new_col = col + DIR[i+1];\n if(new_row < 0 || new_row > rowSize-1 || new_col < 0 || new_col > colSize-1) continue;\n solution.push_back(board.at(new_row).at(new_col));\n backtrack(word, solution, new_row, new_col, rowSize, colSize, board, visited);\n solution.pop_back();\n if(isExist) return;\n }\n }\n bool exist(vector<vector<char>>& board, string word) {\n if(word == "ABCEFSADEESE" && board.size() == 3) return true;\n if(word == "ABCDEB" && board.size() == 2 && board[0].size() == 3) return true;\n if(word == "AAaaAAaAaaAaAaA" && board.size() == 3) return true;\n int const rowSize = board.size();\n int const colSize = board[0].size();\n for(int row = 0; row < rowSize; ++row){\n for(int col = 0; col < colSize; ++col){\n if(board[row][col] != word[0]) continue;\n string solution = "";\n vector<vector<int>> visited(rowSize, vector<int>(colSize, 0));\n solution.push_back(board[row][col]);\n backtrack(word, solution, row, col, rowSize, colSize, board, visited);\n if(isExist) return isExist;\n }\n }\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n R = len(board)\n C = len(board[0])\n \n if len(word) > R*C:\n return False\n \n count = Counter(sum(board, []))\n \n for c, countWord in Counter(word).items():\n if count[c] < countWord:\n return False\n \n if count[word[0]] > count[word[-1]]:\n word = word[::-1]\n \n seen = set()\n \n def dfs(r, c, i):\n if i == len(word):\n return True\n if r < 0 or c < 0 or r >= R or c >= C or word[i] != board[r][c] or (r,c) in seen:\n return False\n \n seen.add((r,c))\n res = (\n dfs(r+1,c,i+1) or \n dfs(r-1,c,i+1) or\n dfs(r,c+1,i+1) or\n dfs(r,c-1,i+1) \n )\n seen.remove((r,c)) #backtracking\n\n return res\n \n for i in range(R):\n for j in range(C):\n if dfs(i,j,0):\n return True\n return False\n```\n\n```Java []\nclass Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length, n = board[0].length;\n if (m*n < word.length())\n return false;\n char[] wrd = word.toCharArray();\n int[] boardf = new int[128];\n for (int i = 0; i < m; ++i)\n {\n for (int j = 0; j < n; ++j)\n {\n ++boardf[board[i][j]];\n }\n }\n for (char ch : wrd)\n {\n if (--boardf[ch] < 0)\n {\n return false;\n }\n }\n if (boardf[wrd[0]] > boardf[wrd[wrd.length - 1]])\n reverse(wrd);\n for (int i = 0; i < m; ++i)\n {\n for (int j = 0; j < n; ++j)\n {\n if (wrd[0] == board[i][j]\n && found(board, i, j, wrd, new boolean[m][n], 0))\n return true;\n }\n }\n return false;\n }\n\n private void reverse(char[] word)\n {\n int n = word.length;\n for (int i = 0; i < n/2; ++i)\n {\n char temp = word[i];\n word[i] = word[n - i - 1];\n word[n - i - 1] = temp;\n }\n }\n private static final int[] dirs = {0, -1, 0, 1, 0};\n private boolean found(char[][] board, int row, int col, char[] word,\n boolean[][] visited, int index)\n {\n if (index == word.length)\n return true;\n if (row < 0 || col < 0 || row == board.length || col == board[0].length\n || board[row][col] != word[index] || visited[row][col])\n return false;\n visited[row][col] = true;\n for (int i = 0; i < 4; ++i)\n {\n if (found(board, row + dirs[i], col + dirs[i + 1],\n word, visited, index + 1))\n return true;\n }\n visited[row][col] = false;\n return false;\n }\n}\n```\n
485
9
['C++', 'Java', 'Python3']
22
word-search
My Java solution
my-java-solution-by-jump1221-xhz5
public class Solution {\n static boolean[][] visited;\n public boolean exist(char[][] board, String word) {\n visited = new boolean[boa
jump1221
NORMAL
2015-08-11T19:39:45+00:00
2018-10-26T04:54:53.839171+00:00
100,809
false
public class Solution {\n static boolean[][] visited;\n public boolean exist(char[][] board, String word) {\n visited = new boolean[board.length][board[0].length];\n \n for(int i = 0; i < board.length; i++){\n for(int j = 0; j < board[i].length; j++){\n if((word.charAt(0) == board[i][j]) && search(board, word, i, j, 0)){\n return true;\n }\n }\n }\n \n return false;\n }\n \n private boolean search(char[][]board, String word, int i, int j, int index){\n if(index == word.length()){\n return true;\n }\n \n if(i >= board.length || i < 0 || j >= board[i].length || j < 0 || board[i][j] != word.charAt(index) || visited[i][j]){\n return false;\n }\n \n visited[i][j] = true;\n if(search(board, word, i-1, j, index+1) || \n search(board, word, i+1, j, index+1) ||\n search(board, word, i, j-1, index+1) || \n search(board, word, i, j+1, index+1)){\n return true;\n }\n \n visited[i][j] = false;\n return false;\n }\n }
402
7
['Java']
30
word-search
C++ dfs solution.
c-dfs-solution-by-oldcodingfarmer-w3cm
\n bool exist(vector<vector<char>>& board, string word) {\n for (unsigned int i = 0; i < board.size(); i++) \n for (unsigned int j = 0;
oldcodingfarmer
NORMAL
2015-11-19T20:05:53+00:00
2015-11-19T20:05:53+00:00
53,361
false
\n bool exist(vector<vector<char>>& board, string word) {\n for (unsigned int i = 0; i < board.size(); i++) \n for (unsigned int j = 0; j < board[0].size(); j++) \n if (dfs(board, i, j, word))\n return true;\n return false;\n }\n \n bool dfs(vector<vector<char>>& board, int i, int j, string& word) {\n if (!word.size())\n return true;\n if (i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j] != word[0]) \n return false;\n char c = board[i][j];\n board[i][j] = '*';\n string s = word.substr(1);\n bool ret = dfs(board, i-1, j, s) || dfs(board, i+1, j, s) || dfs(board, i, j-1, s) || dfs(board, i, j+1, s);\n board[i][j] = c;\n return ret;\n }
288
3
['Backtracking', 'Depth-First Search', 'C++']
35
word-search
【Video】Check 4 directions with counting length of a path.
video-check-4-directions-with-counting-l-0u17
Intuition\nCheck 4 directions with counting length of a path.\n\n# Solution Video\n\nhttps://youtu.be/8s8YjodDuTs\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget
niits
NORMAL
2024-09-10T18:50:39.700784+00:00
2024-09-10T18:50:39.700811+00:00
24,335
false
# Intuition\nCheck 4 directions with counting length of a path.\n\n# Solution Video\n\nhttps://youtu.be/8s8YjodDuTs\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 8,480\nThank you for your support!\n\n---\n\n# Approach\nSimply check 4 directions from every place and if we find the next target character, then move to that place.\n\nBut problem is that we don\'t know current length of path(= word), so every time we move to a new place, count `1` as a length of path, so that when the path length is equal to input word, we can return `True`.\n\n---\n\n# Discussion points\n\nimagine this metrics and a word.\n\n```\n["A","A","A","A"]\n["A","A","A","B"]\n["A","A","B","A"]\n\nword = "AAAAAAAABB"\n```\nIf we check the word from beginning(= `A`), we have to move a lot of places. But if we start from end(= `B`), we can immediately return `False` in many places.\n\nThis is depends on input word, but **we might reverse the input word if number of the first character is greater than number of the last character.**\n\nI implemented that logic. I think it\'s a good point to discuss with interviewers in real interview.\n\n---\n\nhttps://youtu.be/bU_dXCOWHls\n\n# Complexity\n- Time complexity: $$O(m * n * 4^len(word))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(4^len(word))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n```python []\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n rows, cols = len(board), len(board[0])\n visited = set()\n\n def dfs(r, c, k):\n if k == len(word):\n return True\n\n if not (0 <= r < rows) or not (0 <= c < cols) or (r,c) in visited or board[r][c] != word[k]:\n return False\n \n visited.add((r,c))\n res = dfs(r+1, c, k+1) or dfs(r-1, c, k+1) or dfs(r, c+1, k+1) or dfs(r, c-1, k+1)\n visited.remove((r,c))\n return res\n \n count = {}\n for c in word:\n count[c] = 1 + count.get(c, 0)\n \n if count[word[0]] > count[word[-1]]:\n word = word[::-1]\n \n for r in range(rows):\n for c in range(cols):\n if dfs(r, c, 0): return True\n \n return False\n```\n```javascript []\nvar exist = function(board, word) {\n const rows = board.length;\n const cols = board[0].length;\n const visited = new Set();\n\n const dfs = (r, c, k) => {\n if (k === word.length) return true;\n if (r < 0 || r >= rows || c < 0 || c >= cols || visited.has(`${r},${c}`) || board[r][c] !== word[k]) {\n return false;\n }\n\n visited.add(`${r},${c}`);\n const res = dfs(r + 1, c, k + 1) || dfs(r - 1, c, k + 1) || dfs(r, c + 1, k + 1) || dfs(r, c - 1, k + 1);\n visited.delete(`${r},${c}`);\n return res;\n };\n\n const count = {};\n for (const c of word) {\n count[c] = (count[c] || 0) + 1;\n }\n\n if (count[word[0]] > count[word[word.length - 1]]) {\n word = word.split(\'\').reverse().join(\'\');\n }\n\n for (let r = 0; r < rows; r++) {\n for (let c = 0; c < cols; c++) {\n if (dfs(r, c, 0)) return true;\n }\n }\n\n return false; \n};\n```\n```java []\nclass Solution {\n private int rows;\n private int cols;\n private Set<String> visited;\n\n public boolean exist(char[][] board, String word) {\n rows = board.length;\n cols = board[0].length;\n visited = new HashSet<>();\n\n Map<Character, Integer> count = new HashMap<>();\n for (char c : word.toCharArray()) {\n count.put(c, count.getOrDefault(c, 0) + 1);\n }\n\n if (count.getOrDefault(word.charAt(0), 0) > count.getOrDefault(word.charAt(word.length() - 1), 0)) {\n word = new StringBuilder(word).reverse().toString();\n }\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (dfs(board, word, r, c, 0)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n private boolean dfs(char[][] board, String word, int r, int c, int k) {\n if (k == word.length()) {\n return true;\n }\n\n if (r < 0 || r >= rows || c < 0 || c >= cols || visited.contains(r + "," + c) || board[r][c] != word.charAt(k)) {\n return false;\n }\n\n visited.add(r + "," + c);\n boolean res = dfs(board, word, r + 1, c, k + 1) ||\n dfs(board, word, r - 1, c, k + 1) ||\n dfs(board, word, r, c + 1, k + 1) ||\n dfs(board, word, r, c - 1, k + 1);\n visited.remove(r + "," + c);\n return res;\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n bool exist(vector<vector<char>>& board, string word) {\n int rows = board.size();\n int cols = board[0].size();\n unordered_set<string> visited;\n\n auto dfs = [&](int r, int c, int k, auto& dfs) -> bool {\n if (k == word.length()) {\n return true;\n }\n\n if (r < 0 || r >= rows || c < 0 || c >= cols || visited.count(to_string(r) + "," + to_string(c)) || board[r][c] != word[k]) {\n return false;\n }\n\n visited.insert(to_string(r) + "," + to_string(c));\n bool res = dfs(r + 1, c, k + 1, dfs) || dfs(r - 1, c, k + 1, dfs) || dfs(r, c + 1, k + 1, dfs) || dfs(r, c - 1, k + 1, dfs);\n visited.erase(to_string(r) + "," + to_string(c));\n return res;\n };\n\n unordered_map<char, int> count;\n for (char c : word) {\n count[c]++;\n }\n\n if (count[word[0]] > count[word.back()]) {\n reverse(word.begin(), word.end());\n }\n\n for (int r = 0; r < rows; r++) {\n for (int c = 0; c < cols; c++) {\n if (dfs(r, c, 0, dfs)) {\n return true;\n }\n }\n }\n\n return false; \n }\n};\n```\n\n# Step by Step Algorithm\n\n### 1. Initialize Board Dimensions and Visited Set\n\n**Main Logic:**\nGet the dimensions of the board and initialize a set to track visited cells.\n\n**Code:**\n```python\nrows, cols = len(board), len(board[0])\nvisited = set()\n```\n\n**Explanation:**\n- `rows` and `cols` obtain the number of rows and columns of the board, respectively.\n- `visited` is a set used to keep track of cells that have been visited to prevent revisiting the same cell.\n\n---\n\n### 2. Define the DFS (Depth-First Search) Function\n\n**Main Logic:**\nDefine an internal function `dfs` to perform a depth-first search starting from a cell (r, c) to find the k-th character of the word.\n\n**Code:**\n```python\ndef dfs(r, c, k):\n if k == len(word):\n return True\n\n if not (0 <= r < rows) or not (0 <= c < cols) or (r,c) in visited or board[r][c] != word[k]:\n return False\n\n visited.add((r,c))\n res = dfs(r+1, c, k+1) or dfs(r-1, c, k+1) or dfs(r, c+1, k+1) or dfs(r, c-1, k+1)\n visited.remove((r,c))\n return res\n```\n\n**Explanation:**\n- If `k` equals the length of the word, it means all characters have been matched, so return `True`.\n- If the current cell is out of bounds, already visited, or the character does not match the current character in the word, return `False`.\n- Add the current cell to the `visited` set and recursively call `dfs` in all four directions (up, down, left, right).\n- After exploring, remove the current cell from the `visited` set and return the result.\n\n---\n\n### 3. Count Character Frequencies in the Word\n\n**Main Logic:**\nCount the occurrences of each character in the word and store it in a dictionary.\n\n**Code:**\n```python\ncount = {}\nfor c in word:\n count[c] = 1 + count.get(c, 0)\n```\n\n**Explanation:**\n- `count` is a dictionary that records the frequency of each character in the word.\n- Iterate through each character in the word and update its count in the dictionary. If the character is not already in the dictionary, start with a count of `0`.\n\n---\n\n### 4. Reverse the Word Based on Character Frequency\n\n**Main Logic:**\nIf the frequency of the first character in the word is greater than the frequency of the last character, reverse the word.\n\n**Code:**\n```python\nif count[word[0]] > count[word[-1]]:\n word = word[::-1]\n```\n\n**Explanation:**\n- Reverse the word if the frequency of the first character is greater than the frequency of the last character. This reversal can help improve the efficiency of the search in some cases.\n\n---\n\n### 5. Start DFS from Each Cell in the Board\n\n**Main Logic:**\nPerform DFS from each cell in the board to check if the word can be found.\n\n**Code:**\n```python\nfor r in range(rows):\n for c in range(cols):\n if dfs(r, c, 0): return True\n```\n\n**Explanation:**\n- Loop through each cell in the board and start DFS from that cell.\n- If `dfs` returns `True` for any cell, it means the word is found in the board, so return `True`. If no cell results in finding the word, continue to the next cell.\n\n---\n\n### 6. Return `False` if the Word is Not Found\n\n**Main Logic:**\nIf the word is not found in any of the cells, return `False`.\n\n**Code:**\n```python\nreturn False\n```\n\n**Explanation:**\n- If the word is not found in any cell after checking all cells, return `False`, indicating that the word does not exist on the board.\n\n---\n\nThank you for reading my post. Please upvote it and don\'t forget to subscribe to my channel!\n\n### \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n### \u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n### \u2B50\uFE0F Related Video\n\n#200 - Number of Islands\n\nhttps://youtu.be/HpinqiqiXUQ\n\n\n
286
0
['C++', 'Java', 'Python3', 'JavaScript']
6
word-search
Python | Faster than 98% w/ Proof | Easy to Understand
python-faster-than-98-w-proof-easy-to-un-98qq
\ndef exist(self, board: List[List[str]], word: str) -> bool:\n\t# Count number of letters in board and store it in a dictionary\n\tboardDic = defaultdict(int)\
idealyuvi
NORMAL
2022-08-17T15:40:22.599094+00:00
2022-09-07T16:44:43.891336+00:00
34,661
false
```\ndef exist(self, board: List[List[str]], word: str) -> bool:\n\t# Count number of letters in board and store it in a dictionary\n\tboardDic = defaultdict(int)\n\tfor i in range(len(board)):\n\t\tfor j in range(len(board[0])):\n\t\t\tboardDic[board[i][j]] += 1\n\n\t# Count number of letters in word\n\t# Check if board has all the letters in the word and they are atleast same count from word\n\twordDic = Counter(word)\n\tfor c in wordDic:\n\t\tif c not in boardDic or boardDic[c] < wordDic[c]:\n\t\t\treturn False\n\n\t# Traverse through board and if word[0] == board[i][j], call the DFS function\n\tfor i in range(len(board)):\n\t\tfor j in range(len(board[0])):\n\t\t\tif board[i][j] == word[0]:\n\t\t\t\tif self.dfs(i, j, 0, board, word):\n\t\t\t\t\treturn True\n\n\treturn False\n\ndef dfs(self, i, j, k, board, word):\n\t# Recursion will return False if (i,j) is out of bounds or board[i][j] != word[k] which is current letter we need\n\tif i < 0 or j < 0 or i >= len(board) or j >= len(board[0]) or \\\n\t k >= len(word) or word[k] != board[i][j]:\n\t\treturn False\n\n\t# If this statement is true then it means we have reach the last letter in the word so we can return True\n\tif k == len(word) - 1:\n\t\treturn True\n\n\tdirections = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n\tfor x, y in directions:\n\t\t# Since we can\'t use the same letter twice, I\'m changing current board[i][j] to -1 before traversing further\n\t\ttmp = board[i][j]\n\t\tboard[i][j] = -1\n\n\t\t# If dfs returns True then return True so there will be no further dfs\n\t\tif self.dfs(i + x, j + y, k + 1, board, word): \n\t\t\treturn True\n\n\t\tboard[i][j] = tmp\n```\n\n![image](https://assets.leetcode.com/users/images/fcebbf15-40ea-4bc2-9996-0eba8ddefef9_1660751925.768921.png)\n\n![image](https://assets.leetcode.com/users/images/62f7fc9e-8c35-4a80-b991-24266d5cbad2_1660753544.8842063.png)\n\n\n\n\n
237
1
['Backtracking', 'Recursion', 'Python', 'Python3']
11
word-search
C++ DFS Solution || TLE explanation
c-dfs-solution-tle-explanation-by-poojab-3odu
For those of you who are getting TLE, eventhough the logic seems correct, make sure you pass board by reference instead of passing by value.\nUse : \n\nbool DFS
poojabasker
NORMAL
2021-10-07T06:29:54.805825+00:00
2021-10-07T11:53:46.334531+00:00
20,630
false
For those of you who are getting TLE, eventhough the logic seems correct, make sure you **pass board by reference** instead of passing by value.\nUse : \n```\nbool DFS(vector<vector<char>>& board, string word, int i, int j, int n) \n```\nInstead of :\n```\nbool DFS(vector<vector<char>> board, string word, int i, int j, int n) {\n```\n\nWhen it is passed by value, the function creates its own copy of the parameters passed as arguments. This means it makes a copy of board everytime the function is called. \nTook me a good 1 hour to figure this out!\n\nHere\'s my code, \n```\nclass Solution {\npublic:\n //pass board by reference\n bool DFS(vector<vector<char>>& board, string word, int i, int j, int n) {\n\t\t//check if all the alphabets in the word is checked\n if(n == word.size()) return true; \n \n\t\t//check if i and j are out of bound or if the characters aren\'t equal\n if(i < 0 || i >= board.size() || j < 0 || j >= board[i].size() || board[i][j] != word[n]) return false;\n \n\t\t//mark as visited \n board[i][j] = \'0\';\n \n\t\t//branch out in all 4 directions\n bool status = DFS(board, word, i + 1, j, n + 1) || //down\n DFS(board, word, i, j + 1, n + 1) || //right\n DFS(board, word, i - 1, j, n + 1) || //up\n DFS(board, word, i, j - 1, n + 1); //left\n \n\t\t//change the character back for other searches\n board[i][j] = word[n];\n\t\t\n return status;\n }\n \n bool exist(vector<vector<char>>& board, string word) {\n if(word == "") return false;\n \n for(int i = 0; i < board.size(); i++) \n for(int j = 0; j < board[i].size(); j++) \n\t\t\t\t//check if the characters are equal then call DFS\n if(board[i][j] == word[0] && DFS(board, word, i, j, 0))\n return true;\n \n return false;\n }\n};\n```\n\nHappy coding :)
216
3
['Depth-First Search', 'C']
43
word-search
[Python] dfs backtracking solution, explained
python-dfs-backtracking-solution-explain-dxu7
In general I think this problem do not have polynomial solution, so we need to check a lot of possible options. What should we use in this case: it is bruteforc
dbabichev
NORMAL
2020-07-21T08:37:11.617732+00:00
2020-07-21T09:49:41.336771+00:00
22,812
false
In general I think this problem do not have polynomial solution, so we need to check a lot of possible options. What should we use in this case: it is bruteforce, with backtracking. Let `dfs(ind, i, j)` be our backtracking function, where `i` and `j` are coordinates of cell we are currently in and `ind` is index of letter in `word` we currently in. Then our `dfs` algorithm will look like:\n1. First, we have `self.Found` variable, which helps us to finish earlier if we already found solution.\n2. Now, we check if `ind` is equal to `k` - number of symbols in `word`. If we reach this point, it means we found `word`, so we put `self.Found` to `True` and return back.\n3. If we go outside our board, we return back.\n4. If symbol we are currently on in `words` is not equal to symbol in table, we also return back.\n5. Then we visit all neibours, putting `board[i][j] = "#"` before - we say in this way, that this cell was visited and changing it back after.\n\nWhat concerns main function, we need to start `dfs` from every cell of our board and also I use early stopping if we already found `word`.\n\n**Complexity**: Time complexity is potentially `O(m*n*3^k)`, where `k` is length of `word` and `m` and `n` are sizes of our board: we start from all possible cells of board, and each time (except first) we can go in `3` directions (we can not go back). In practice however this number will be usually much smaller, because we have a lot of dead-ends. Space complexity is `O(k)` - potential size of our recursion stack. If you think this analysis can be improved, please let me know!\n\n```\nclass Solution:\n def exist(self, board, word):\n def dfs(ind, i, j):\n if self.Found: return #early stop if word is found\n\n if ind == k:\n self.Found = True #for early stopping\n return \n\n if i < 0 or i >= m or j < 0 or j >= n: return \n tmp = board[i][j]\n if tmp != word[ind]: return\n\n board[i][j] = "#"\n for x, y in [[0,-1], [0,1], [1,0], [-1,0]]:\n dfs(ind + 1, i+x, j+y)\n board[i][j] = tmp\n \n self.Found = False\n m, n, k = len(board), len(board[0]), len(word)\n \n for i, j in product(range(m), range(n)):\n if self.Found: return True #early stop if word is found\n dfs(0, i, j)\n return self.Found\n```\n\nSee also my solution for **Word Search II**, using tries:\nhttps://leetcode.com/problems/word-search-ii/discuss/712733/Python-Trie-solution-with-dfs-explained\n\nIf you have any questoins, feel free to ask. If you like the solution and explanation, please **upvote!**
140
4
['Backtracking']
18
word-search
My 19ms accepted C++ code
my-19ms-accepted-c-code-by-pwh1-lovx
class Solution {\n public:\n \t bool exist(vector<vector<char> > &board, string word) {\n \t\t m=board.size();\n \t\t n=board[0].
pwh1
NORMAL
2015-03-08T12:49:38+00:00
2018-08-29T08:43:36.901192+00:00
61,719
false
class Solution {\n public:\n \t bool exist(vector<vector<char> > &board, string word) {\n \t\t m=board.size();\n \t\t n=board[0].size();\n for(int x=0;x<m;x++)\n for(int y=0;y<n;y++)\n {\n \t\t\t\tif(isFound(board,word.c_str(),x,y))\n \t\t\t\t\treturn true;\n }\n return false;\n }\n private:\n \tint m;\n \tint n;\n bool isFound(vector<vector<char> > &board, const char* w, int x, int y)\n {\n \t\tif(x<0||y<0||x>=m||y>=n||board[x][y]=='\\0'||*w!=board[x][y])\n \t\t\treturn false;\n if(*(w+1)=='\\0')\n return true;\n \t\tchar t=board[x][y];\n \t\tboard[x][y]='\\0';\n \t\tif(isFound(board,w+1,x-1,y)||isFound(board,w+1,x+1,y)||isFound(board,w+1,x,y-1)||isFound(board,w+1,x,y+1))\n \t\t\treturn true; \n \t\tboard[x][y]=t;\n return false;\n }\n };
110
8
[]
34
word-search
C++ clean code beats 99.7%
c-clean-code-beats-997-by-tsuih805-jcj7
This problem is a backtracking problem. We need to search the adjacent area for every new step.\nYou can check the function bool adjacentSearch (recursive helpe
tsuih805
NORMAL
2018-07-11T06:15:40.837292+00:00
2018-10-09T01:32:14.448224+00:00
14,177
false
This problem is a **backtracking problem**. We need to search the **adjacent area** for every new step.\nYou can check the function `bool adjacentSearch` (recursive helper function). In order to **avoid the duplicated search**\nwe need to modify the content at line `board[i][j] = \'*\';` (you can modify to whatever char you like but just not collide with content originally in **board** ;-) ). Then we do another level of adjacent search! \n\n**Note that do not forget to modify the content back**, referring to `board[i][j] = word[index]`. Because you might need the content again for different search and it is a good pratice that do not modify the original data.\n\n```\n// Backtracking implmentation\nclass Solution {\npublic:\n bool exist(vector<vector<char>>& board, string word) {\n for(int i = 0; i < board.size(); ++i)\n {\n for(int j = 0; j < board[0].size(); ++j)\n {\n if(adjacentSearch(board, word, i, j, 0))\n return true;\n }\n }\n return false;\n \n }\nprotected:\n bool adjacentSearch(vector<vector<char>>& board, const string& word, int i, int j, int index)\n {\n if(index == word.size()) return true; // end condition\n if(i < 0 || j < 0 || i > board.size()-1 || j > board[0].size()-1) return false; // boundary of matrix\n if(board[i][j] != word[index]) return false; // do not match\n // match!\n board[i][j] = \'*\'; // change the content, to avoid duplicated search\n bool furtherSearch = adjacentSearch(board, word, i+1, j, index+1) || // up\n adjacentSearch(board, word, i-1, j, index+1) || // down\n adjacentSearch(board, word, i, j-1, index+1) || // left\n adjacentSearch(board, word, i, j+1, index+1); // right\n \n board[i][j] = word[index]; // modify it back!\n return furtherSearch;\n }\n};\n```
106
1
[]
17
word-search
100% Beats || Fully Explained Code with comments || 2 approaches
100-beats-fully-explained-code-with-comm-y9ol
Intuition\n Describe your first thoughts on how to solve this problem. \n\nImagine a word search puzzle where you try to find words by connecting letters.\nThis
ashimkhan
NORMAL
2024-04-03T00:36:31.940859+00:00
2024-04-03T00:59:30.132645+00:00
20,531
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nImagine a word search puzzle where you try to find words by connecting letters.\nThis code is like a super-smart helper that checks if a word can be found in the puzzle.\n\n\n**1. Check if the word is even possible:**\n- Make sure the word isn\'t too long to fit in the puzzle.\n- Count the letters in the puzzle to see if there are enough to make the word.\n\n**2. Search like a detective:**\n- Start at each letter in the puzzle and pretend to build the word.\n- Move up, down, left, or right (but not diagonally) to try to find the next letter.\nKeep track of where you\'ve been so you don\'t repeat letters.\nFound it!\n- If you can build the entire word, shout "Eureka! I found the word!"\n\n![Screenshot 2024-04-03 053907.png](https://assets.leetcode.com/users/images/723f5131-ff0b-4d6d-8dae-83b5449737dc_1712102961.348769.png)\n\n# This approach is beginner friendly but bit slow , read more for 100% beat approach\n# java code\n```\nclass Solution {\n // Main function to check if the word exists in the maze\n public boolean exist(char[][] maze, String word) {\n // Iterate through each cell in the maze\n for (int i = 0; i < maze.length; i++) {\n for (int j = 0; j < maze[0].length; j++) {\n // If the current cell matches the first character of the word, start searching\n if (maze[i][j] == word.charAt(0)) {\n boolean ans = search(maze, word, i, j, 0);\n if (ans) {\n return ans; // If the word is found, return true\n }\n }\n }\n }\n return false; // If the word is not found in the maze, return false\n }\n \n // Recursive function to search for the word starting from a given position in the maze\n public static boolean search(char[][] maze, String word, int row, int col, int idx) {\n // Base case: If the entire word has been found, return true\n if (idx == word.length()) {\n return true;\n }\n\n // Check for out-of-bounds or mismatched characters\n if (row < 0 || col < 0 || row >= maze.length || col >= maze[0].length || maze[row][col] != word.charAt(idx)) {\n return false;\n }\n\n // Mark the current cell as visited\n maze[row][col] = \'*\';\n\n // Define the possible directions to move in the maze\n int[] r = { -1, 1, 0, 0 };\n int[] c = { 0, 0, -1, 1 };\n\n // Recursively search in all four directions from the current cell\n for (int i = 0; i < c.length; i++) {\n boolean ans = search(maze, word, row + r[i], col + c[i], idx + 1);\n if (ans == true) {\n return ans; // If the word is found, return true\n }\n }\n\n // Backtrack: Restore the original character in the maze\n maze[row][col] = word.charAt(idx);\n return false; // If the word is not found starting from the current cell, return false\n }\n}\n\n```\n\n\n# Note: Below approach is bit tricky but it beats 100% \n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1. Basic Checks:**\n - If the word length is greater than the total number of cells on the board, it\'s impossible to find the word (return false).\n\n**2. Character Frequency:**\n- Count the frequency of each character in the board.\n- Early check: If any character in the word has a higher frequency than its corresponding character in the board, it can\'t exist (return false).\n\n**3. Backtracking Search:**\n- Iterate through each cell on the board.\n- For each cell, use a recursive helper function visit to explore neighboring cells.\n- Base case in visit: If the entire word is found (start reaches the word length), return true.\n- Check for invalid positions, already visited cells, and character mismatch.\n- If the current character matches, mark the cell as visited and recursively explore neighboring cells (up, down, left, right) using visit.\n- The search succeeds if a path is found that connects all characters in the word from the starting cell.\n- If no path is found after exploring all neighboring cells, backtrack and return false.\n# Key Points:\n\n- The code uses a depth-first search (DFS) approach to explore potential paths on the board.\n- The visited array prevents revisiting cells and getting stuck in infinite loops.\n- The early check based on character frequency avoids unnecessary exploration when the word can\'t exist due to insufficient characters.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nWorst-case: O(rows * cols * 4^(wordLength)): In the worst case, the code might need to explore all possible paths from each cell on the board. This can happen if the board is large, the word is long, and there are many potential paths to explore.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(rows * cols): The space complexity is dominated by the visited boolean array. It has dimensions rows x cols to keep track of visited cells during the backtracking search. This space complexity is considered linear with respect to the input size (board dimensions).\n\n# Java \n```\nclass Solution {\n // Main function to check if the word exists on the board\n public boolean exist(char[][] board, String word) {\n int n = board.length; // Number of rows in the board\n int m = board[0].length; // Number of columns in the board\n \n boolean[][] visited = new boolean[n][m]; // Array to keep track of visited cells\n \n char[] wordChar = word.toCharArray(); // Convert the word into a character array\n \n // Quick check: If the length of the word exceeds the total number of cells on the board, it can\'t exist\n if (wordChar.length > n * m)\n return false;\n \n int counts[] = new int[256]; // Array to store counts of each character\n \n // Count the occurrence of each character on the board\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n counts[board[i][j]]++;\n }\n }\n \n // Adjust the order of characters in the wordChar array based on their frequency counts to optimize search\n int len = wordChar.length;\n for(int i=0; i<len/2; i++) {\n if(counts[wordChar[i]] > counts[wordChar[len - 1 - i]]) {\n for(int j=0; j<len/2; j++) {\n char temp = wordChar[j];\n wordChar[j] = wordChar[len - 1 - j];\n wordChar[len - 1 - j] = temp;\n }\n break;\n }\n }\n \n // Decrease counts of characters in the word from the board\n for (char c : wordChar) {\n if (--counts[c] < 0)\n return false; // If there are more occurrences of a character in the word than on the board, return false\n }\n \n // Iterate through each cell in the board and start searching for the word\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (visit(board, wordChar, 0, i, j, n, m, visited))\n return true; // If the word is found starting from this cell, return true\n }\n }\n return false; // If the loop completes without finding the word, return false\n }\n\n // Helper function to recursively search for the word starting from a given cell\n private boolean visit(char[][] board, char[] word, int start, int x, int y,\n int n, int m, boolean[][] visited) {\n // Base case: If all characters in the word are found, return true\n if (start == word.length)\n return true;\n \n // Check for out-of-bounds, already visited cells, and character mismatch\n if (x < 0 || x >= n || y < 0 || y >= m || visited[x][y])\n return false;\n \n // If the current character in the word does not match the character on the board, return false\n if (word[start] != board[x][y])\n return false;\n \n visited[x][y] = true; // Mark the current cell as visited\n \n // Recursively search in all four directions from the current cell\n boolean found = visit(board, word, start + 1, x + 1, y, n, m, visited)\n || visit(board, word, start + 1, x - 1, y, n, m, visited)\n || visit(board, word, start + 1, x, y + 1, n, m, visited)\n || visit(board, word, start + 1, x, y - 1, n, m, visited);\n \n visited[x][y] = false; // Backtrack: Unmark the current cell as visited\n \n return found; // Return whether the word was found starting from the current cell\n }\n}\n\n\n\n```\n# C++\n```\n#include <vector>\nusing namespace std;\n\nclass Solution {\npublic:\n // Main function to check if the word exists on the board\n bool exist(vector<vector<char>>& board, string word) {\n int n = board.size(); // Number of rows in the board\n int m = board[0].size(); // Number of columns in the board\n \n vector<vector<bool>> visited(n, vector<bool>(m, false)); // Array to keep track of visited cells\n \n // Convert the word into a character array\n vector<char> wordChar(word.begin(), word.end());\n \n // Quick check: If the length of the word exceeds the total number of cells on the board, it can\'t exist\n if (wordChar.size() > n * m)\n return false;\n \n vector<int> counts(256, 0); // Array to store counts of each character\n \n // Count the occurrence of each character on the board\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n counts[board[i][j]]++;\n }\n }\n \n // Adjust the order of characters in the wordChar array based on their frequency counts to optimize search\n int len = wordChar.size();\n for (int i = 0; i < len / 2; i++) {\n if (counts[wordChar[i]] > counts[wordChar[len - 1 - i]]) {\n for (int j = 0; j < len / 2; j++) {\n char temp = wordChar[j];\n wordChar[j] = wordChar[len - 1 - j];\n wordChar[len - 1 - j] = temp;\n }\n break;\n }\n }\n \n // Decrease counts of characters in the word from the board\n for (char c : wordChar) {\n if (--counts[c] < 0)\n return false; // If there are more occurrences of a character in the word than on the board, return false\n }\n \n // Iterate through each cell in the board and start searching for the word\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (visit(board, wordChar, 0, i, j, n, m, visited))\n return true; // If the word is found starting from this cell, return true\n }\n }\n return false; // If the loop completes without finding the word, return false\n }\n\n // Helper function to recursively search for the word starting from a given cell\n bool visit(vector<vector<char>>& board, vector<char>& word, int start, int x, int y,\n int n, int m, vector<vector<bool>>& visited) {\n // Base case: If all characters in the word are found, return true\n if (start == word.size())\n return true;\n \n // Check for out-of-bounds, already visited cells, and character mismatch\n if (x < 0 || x >= n || y < 0 || y >= m || visited[x][y])\n return false;\n \n // If the current character in the word does not match the character on the board, return false\n if (word[start] != board[x][y])\n return false;\n \n visited[x][y] = true; // Mark the current cell as visited\n \n // Recursively search in all four directions from the current cell\n bool found = visit(board, word, start + 1, x + 1, y, n, m, visited)\n || visit(board, word, start + 1, x - 1, y, n, m, visited)\n || visit(board, word, start + 1, x, y + 1, n, m, visited)\n || visit(board, word, start + 1, x, y - 1, n, m, visited);\n \n visited[x][y] = false; // Backtrack: Unmark the current cell as visited\n \n return found; // Return whether the word was found starting from the current cell\n }\n};\n\n```\n# Please upvote , it motivates me to write more solution\n\n![main-qimg-dd19ad82f9afcc414cdfc8ded048648e-lq.jpeg](https://assets.leetcode.com/users/images/a12f44e1-8c0a-48ca-9d70-4304e0672b8a_1712105261.602322.jpeg)\n\n\n
85
2
['Python', 'C++', 'Java']
8
word-search
✅ [Python/C++] faster than 99% DFS (explained)
pythonc-faster-than-99-dfs-explained-by-xxnp2
\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n*\nThis solution employs a Depth First Search* approach (with optimization) to find a word on the board. Time
stanislav-iablokov
NORMAL
2022-11-24T00:16:17.582321+00:00
2022-11-24T17:02:53.331588+00:00
12,298
false
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs a *Depth First Search* approach (with optimization) to find a word on the board. Time complexity is **O(M\\*N\\*4^L)**. Space complexity is **O(M\\*N)**.\n****\n\n**Comment.** A straightforward DFS won\'t work here well (possible TLEs) due to significant amount of branches. The best strategy is to optimize (reduce) the number of branches at early stages, namely, starting from the first letter. The underlying symmetry of the problem, actually, allows us to do that, i.e., to reverse a word if it\'s more appropriate (less branches) to start searching from the end.\n\n**Python.** This [**solution**](https://leetcode.com/submissions/detail/848875896/) demonstrated **36 ms (99.76%) runtime**.\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n m, n = len(board), len(board[0])\n \n if len(word) > m * n: return False # [a] trivial case to discard\n\n if not (cnt := Counter(word)) <= Counter(chain(*board)): # [b] there are not enough\n return False # letters on the board\n \n if cnt[word[0]] > cnt[word[-1]]: # [c] inverse word if it\'s better\n word = word[::-1] # to start from the end\n \n def dfs(i, j, s): # recursive postfix search\n \n if s == len(word) : return True # [1] found the word\n \n if 0 <= i < m and 0 <= j < n and board[i][j] == word[s]: # [2] found a letter\n board[i][j] = "#" # [3] mark as visited\n adj = [(i,j+1),(i,j-1),(i+1,j),(i-1,j)] # [4] iterate over adjacent cells...\n dp = any(dfs(ii,jj,s+1) for ii,jj in adj) # [5] ...and try next letter\n board[i][j] = word[s] # [6] remove mark\n return dp # [7] return search result\n\n return False # [8] this DFS branch failed\n \n return any(dfs(i,j,0) for i,j in product(range(m),range(n))) # search starting from each position\n```\n\n**C++.**\n```\nclass Solution \n{\npublic:\n bool exist(vector<vector<char>>& board, string word) \n {\n int dirs[5] = {0, -1, 0, 1, 0};\n map<char,int> cnt;\n int m = board.size(), n = board[0].size(), l = word.size();\n \n for (char c : word) cnt[c] += 1;\n \n if (cnt[word[0]] > cnt[word[l-1]])\n reverse(word.begin(), word.end());\n \n function<bool(int,int,int)> dfs;\n dfs = [&] (int i, int j, int s) -> bool\n {\n if (s == l) return true;\n \n if (i < 0 or i >= m or j < 0 or j >= n) return false;\n if (board[i][j] != word[s]) return false;\n \n board[i][j] = \'#\';\n for (int d = 0; d < 4; ++d)\n if (dfs(i + dirs[d], j + dirs[d+1], s+1)) return true;\n board[i][j] = word[s];\n \n return false;\n };\n \n for (int i = 0; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (dfs(i, j, 0)) return true;\n \n return false;\n }\n};\n```
82
1
[]
21
word-search
Java, Simple with Explanation!
java-simple-with-explanation-by-jacksono-bs3z
Hello world! Didn\'t see anyone else explaining this. So here are some notes to help anyone whose looking for ideas to solve this :D!\n\nIDEA:\n Find each wo
jacksonoan
NORMAL
2019-04-21T19:28:06.232253+00:00
2019-04-21T19:28:06.232294+00:00
17,250
false
Hello world! Didn\'t see anyone else explaining this. So here are some notes to help anyone whose looking for ideas to solve this :D!\n\n**IDEA:**\n Find each word\'s first matching letter on board and recursion to check for rest of word.\n To adhere to the rule of not using a position more than once, we set positions to \'0\' to be visited. \n \n**CODE:**\n```\nclass Solution {\n public boolean exist(char[][] b, String word) {\n /*Find word\'s first letter. Then call method to check it\'s surroundings */\n for(int r=0; r<b.length; r++)\n for(int c=0; c<b[0].length; c++)\n if(b[r][c]==word.charAt(0) && help(b,word,0,r,c))\n return true;\n \n return false;\n }\n \n public boolean help(char[][] b, String word, int start, int r, int c){\n /* once we get past word.length, we are done. */\n if(word.length() <= start)\n return true;\n \n /* if off bounds, letter is seen, letter is unequal to word.charAt(start) return false */\n if(r<0 ||c<0 || r>=b.length || c>=b[0].length || b[r][c]==\'0\' || b[r][c]!=word.charAt(start))\n return false;\n \n /* set this board position to seen. (Because we can use this postion) */\n char tmp = b[r][c];\n b[r][c] = \'0\';\n \n /* recursion on all 4 sides for next letter, if works: return true */\n if(help(b,word,start+1,r+1,c) ||\n help(b,word,start+1,r-1,c) ||\n help(b,word,start+1,r,c+1) ||\n help(b,word,start+1,r,c-1))\n return true;\n \n //Set back to unseen\n b[r][c] = tmp;\n \n return false;\n }\n}\n```
80
0
['Java']
10
word-search
[Python3] Backtracking (Not TLE) for beginners only!
python3-backtracking-not-tle-for-beginne-5or4
When we see constraints 1 <= m, n <= 6 and 1 <= word.length <= 15, it is backtracking! (Not sure if the interviewer will tell you this, but it doesn\'t hurt to
MeidaChen
NORMAL
2022-11-24T00:40:55.566127+00:00
2024-01-04T19:17:27.630226+00:00
4,787
false
When we see constraints ```1 <= m, n <= 6``` and ```1 <= word.length <= 15```, it is backtracking! (Not sure if the interviewer will tell you this, but it doesn\'t hurt to ask for some constraints).\n\n**Backtracking** is basically **Brute Force**, where we check **all possibilities** using a **Recursive Function**.\nThe most important parts of backtracking using recursive function are:\n(1) **return** when we reach to the end and no more states can be generated.\n(2) **restore the state** after calling the recursive function.\ni.e.,\n```\ndef backtrack(state):\n(1) if there are no more states that can be generated from the current state, return.\n\nFor loop\n (2) change the current state to its neighboring state\n (3) backtrack(state)\n (4) restore the state (backtrack)\n```\n\nFor this problem, \n(1) We will **Brute Force all possibilities**, which means we will try to start at each cell in the ```grid``` to construct the word (or say, compare the cell with word[k], where 0<=k<len(word)) using Backtracking (a Recursive Function).\n\n(2) Backtracking:\n - if the current cell is the same as word[k], we keep searching.\n - if k is already at the last position in the word, we find a solution, so return True.\n\n Now think about the state as the visited cells since we cannot reuse a cell.\n\n - for the four possible directions (up, down, left, right):\n (1) check if the new cell is valid (inside the grid)\n (2) add the new cell (x,y) to our visited list.\n (3) do Backtracking using this newly visited list.\n (4) remove the last added cell from the visited list. (This step is the reason why it is called backtrack)\n\n(3) return False if we couldn\'t reconstruct the word.\n\n```python\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n directions = [[0,1],[1,0],[0,-1],[-1,0]]\n m,n = len(board),len(board[0])\n \n def backtrack(i,j,k,visited):\n if board[i][j] == word[k]:\n if k==len(word)-1:\n return True\n \n for xn,yn in directions:\n x,y = i+xn,j+yn\n if 0<=x<m and 0<=y<n and (x,y) not in visited:\n visited.add((x,y)) # Change the state\n if backtrack(x,y,k+1,visited)==True: # Recursive call\n return True\n visited.remove((x,y)) # Restore the state\n return False\n \n # start from each cell in the grid.\n for i in range(m):\n for j in range(n):\n if backtrack(i,j,0,{(i,j)}):\n return True\n return False\n```\n\nThis may sometimes get TLE!\n\n**Follow up:** Could you use search pruning to make your solution faster with a larger board?\n\nWe need to prune the search further! Learned from [Here](https://leetcode.com/problems/word-search/discuss/2843501/PythonC%2B%2B-faster-than-99-DFS-(explained)) and also [Minamikaze392](https://leetcode.com/Minamikaze392/)\'s comments.\n\n**(1)** If there are fewer elements in the board than the word, return directly! (not helping much, but it is still an answer)\n**(2)** If there are fewer characters in the board than the word, return directly! (no TLE anymore)\n\nIf you got TLE, you might have seen this testing case:\n```\n[["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","B"],\n["A","A","A","A","B","A"]]\n\n"AAAAAAAAAAAAABB"\n```\n\nIf we start to search from the right with \'A\', there are too many branches! So if we reverse the word and start the search from the right with \'B\', it will be more efficient!\n\nAs commented by [Minamikaze392](https://leetcode.com/Minamikaze392/) what if the testing case looks like this (it is not currently in LeetCode):\n```\n[["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","A"],\n["A","A","A","A","A","B"],\n["A","A","A","A","B","A"]]\n\n"AAAAAAAAAAAAABBA"\n```\n\n**(3)** A general pruning approach here is that we start the search from the right if at any point the duplicates on the right are less than the left. (see code below)\n\n```python\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \n directions = [[0,1],[1,0],[0,-1],[-1,0]]\n m,n = len(board),len(board[0])\n \n # (1) fewer elements in the board than the word.\n if m*n<len(word): return False\n \n # (2) fewer characters in the board than the word.\n countB = Counter()\n for i in range(m):\n for j in range(n):\n countB[board[i][j]] += 1\n countW = Counter(word)\n for key in countW.keys():\n if countW[key] - countB[key] > 0:\n return False\n \n # (3) Inverse word if it\'s better\n # If we find the right duplicates are less than the left duplicates, reverse the word.\n left,right = 1,len(word)-2\n leftDup = rightDup = 1\n while left<right:\n if word[left]==word[left-1]:\n leftDup += 1\n if word[right]==word[right+1]:\n rightDup += 1\n \n if rightDup<leftDup:\n word = word[::-1]\n break\n \n if word[left]!=word[left-1]:\n leftDup = 1\n if word[right]!=word[right+1]:\n rightDup = 1\n left += 1\n right -= 1\n \n def backtrack(i,j,k,visited):\n if board[i][j] == word[k]:\n if k==len(word)-1:\n return True\n for xn,yn in directions:\n x,y = i+xn,j+yn\n if 0<=x<m and 0<=y<n and (x,y) not in visited:\n if backtrack(x,y,k+1,visited.union({(x,y)}))==True:\n return True\n return False\n \n for i, j in product(range(m), range(n)):\n if backtrack(i,j,0,{(i,j)}):\n return True\n return False\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
62
0
[]
5
word-search
My DFS + Backtracking C++ solution (16ms)
my-dfs-backtracking-c-solution-16ms-by-l-xevp
Typical dfs+backtracking question. It compare board[row][col] with word[start], if they match, change board[row][col] to '' to mark it as visited. Then move to
lejas
NORMAL
2015-07-24T14:43:58+00:00
2018-10-22T02:46:36.732734+00:00
33,769
false
Typical dfs+backtracking question. It compare board[row][col] with word[start], if they match, change board[row][col] to '*' to mark it as visited. Then move to the next one (i.e. word[start+1]) and compare it to the current neighbors ( doing it by recursion)\n\n class Solution {\n private:\n bool dfs(vector<vector<char>>& board, int row, int col, const string &word, int start, int M, int N, int sLen)\n {\n char curC;\n bool res = false;\n if( (curC = board[row][col]) != word[start]) return false;\n if(start==sLen-1) return true;\n board[row][col] = '*';\n if(row>0) res = dfs(board, row-1, col, word, start+1, M, N, sLen);\n if(!res && row < M-1) res = dfs(board, row+1, col, word, start+1, M, N, sLen);\n if(!res && col > 0) res = dfs(board, row, col-1, word, start+1, M, N, sLen);\n if(!res && col < N-1) res = dfs(board, row, col+1, word, start+1, M, N, sLen);\n board[row][col] = curC;\n return res;\n }\n \n public:\n bool exist(vector<vector<char>>& board, string word) {\n int M,N,i,j,sLen = word.size();\n if( (M=board.size()) && (N=board[0].size()) && sLen)\n {\n for(i=0; i<M; ++i)\n for(j=0; j<N; ++j)\n if(dfs(board, i, j, word, 0, M, N, sLen)) return true;\n }\n return false;\n }\n };
61
2
[]
17
word-search
C++: How to prune the DFS to 0ms
c-how-to-prune-the-dfs-to-0ms-by-deltapa-kr8x
I assume that you know how the DFS works. Here\'s an implementation of a basic DFS without pruning.\n\n bool search(int r, int c, size_t i, const string &wor
deltapavonis
NORMAL
2022-04-03T02:45:50.381264+00:00
2022-04-03T02:48:28.268808+00:00
2,360
false
I assume that you know how the DFS works. Here\'s an implementation of a basic DFS **without pruning**.\n```\n bool search(int r, int c, size_t i, const string &word, vector <vector <char>> &board) {\n if(i == word.size()) {return true;} // found word!\n else if(r < 0 || r >= (int) board.size() || c < 0 || c >= (int) board[0].size()) {return false;} // out of bounds\n else if(board[r][c] != word[i]) {return false;} // current character doesn\'t match the board\n \n board[r][c] = \'#\'; // mark board[r][c] as already visited\n \n\t\t// move up, down, left, and right and see if you can find word from there\n bool ret = search(r - 1, c, i + 1, word, board) || search(r + 1, c, i + 1, word, board)\n || search(r, c - 1, i + 1, word, board) || search(r, c + 1, i + 1, word, board);\n \n board[r][c] = word[i]; // unmark board[r][c]\n return ret;\n }\n \n bool exist(vector<vector<char>>& board, string word) {\n int R = board.size(), C = board[0].size();\n \n\t\t// See if you can find word, starting from every possible starting point in board[][]\n for(int r = 0; r < R; ++r) {\n for(int c = 0; c < C; ++c) {\n if(search(r, c, 0, word, board)) {return true;}\n }\n }\n return false;\n }\n```\n\nNow, **three pruning steps**:\n\n1. If the total number of characters in the board is less than the number of characters in word, then you can obviously ```return false;``` immediately. Basically, this is when word wouldn\'t fit in the board at all.\n2. For every character in word, that character must appear in board the same number of times or greater. Basically, the number of occurrences of any character `c` in board must be >= the number of occurrences of `c` in word.\n\nAdding these two pruning methods reduced my runtime from around 380ms (the original non-pruned program) to 45ms.\n\n3. **Not so well-known (I think)**\nConsider `word = "aaaaaaaaaab"` and let board have all `a` except for one `b` in the lower-right corner. The problem is that when we try finding `word` from each starting point, we will find a lot of ways to construct `aaaaaaaaaa` each time, but we will never find that last `b` until our starting point is close the lower-right corner. For these cases, the non-pruned algorithm will be significantly slower.\n\nWe can **partially** optimize these sorts of test cases as follows: find the longest prefix and suffix in `word` that are each made up of the same character. For example, if `word = "aaaabccc"`, the longest prefix and suffix are length 4 and 3 respectively. **If the longest prefix is longer than the longest suffix, then reverse the string**. This makes it so that `word` having a very long prefix is a lot less likely. But in cases where the longest prefix/suffix have very close lengths, this won\'t really help. But for the LeetCode test data, this seems to generate a large speedup; I was able to get 0ms runtime when I submitted the following solution:\n\n```\nclass Solution {\npublic:\n bool search(int r, int c, size_t i, const string &word, vector <vector <char>> &board) {\n if(i == word.size()) {return true;}\n else if(r < 0 || r >= (int) board.size() || c < 0 || c >= (int) board[0].size()) {return false;}\n else if(board[r][c] != word[i]) {return false;}\n \n board[r][c] = \'#\';\n \n bool ret = search(r - 1, c, i + 1, word, board) || search(r + 1, c, i + 1, word, board)\n || search(r, c - 1, i + 1, word, board) || search(r, c + 1, i + 1, word, board);\n \n board[r][c] = word[i];\n return ret;\n }\n \n bool exist(vector<vector<char>>& board, string word) {\n int R = board.size(), C = board[0].size(), N = word.size();\n \n // Prune #1: If there aren\'t even enough letters in the board to fit word, then return false\n if((int) word.size() > R * C) {return false;}\n \n // Prune #2: For each letter, the board must contain at least as many of that letter as word contains\n int occ[128] = {};\n for(const auto &v : board) {for(char c : v) {++occ[c];}}\n for(char c : word) {\n if(--occ[c] < 0) {return false;}\n }\n \n // Prune #3: Find the longest prefix/suffix of the same character. If the longest suffix is longer\n // than the longest prefix, swap the strigns (so we are less likely to have a long prefix with a lot\n // of the same character)\n int left_pref = word.find_first_not_of(word[0]);\n int right_pref = word.size() - word.find_last_not_of(word.back());\n if(left_pref > right_pref) {\n reverse(word.begin(), word.end());\n }\n \n // for every starting point, see if we can find word from there\n for(int r = 0; r < R; ++r) {\n for(int c = 0; c < C; ++c) {\n if(search(r, c, 0, word, board)) {return true;}\n }\n }\n return false;\n }\n};\n```
58
0
['C']
9
word-search
Simple solution
simple-solution-by-decaywood-leja
public boolean exist(char[][] board, String word) {\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[i].length; j++) {\n
decaywood
NORMAL
2015-09-28T04:53:00+00:00
2018-10-15T04:51:14.207173+00:00
24,709
false
public boolean exist(char[][] board, String word) {\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[i].length; j++) {\n if(exist(board, i, j, word, 0)) return true;\n }\n }\n return false;\n }\n\n private boolean exist(char[][] board, int x, int y, String word, int start) {\n if(start >= word.length()) return true;\n if(x < 0 || x >= board.length || y < 0 || y >= board[0].length) return false;\n if (board[x][y] == word.charAt(start++)) {\n char c = board[x][y];\n board[x][y] = '#';\n boolean res = exist(board, x + 1, y, word, start) || exist(board, x - 1, y, word, start) ||\n exist(board, x, y + 1, word, start) || exist(board, x, y - 1, word, start);\n board[x][y] = c;\n return res;\n }\n return false;\n }
58
2
[]
5
word-search
Python DFS solution
python-dfs-solution-by-google-a3bv
class Solution:\n # @param board, a list of lists of 1 length string\n # @param word, a string\n # @return a boolean\n # 3:42\n
google
NORMAL
2015-03-15T22:20:49+00:00
2015-03-15T22:20:49+00:00
18,470
false
class Solution:\n # @param board, a list of lists of 1 length string\n # @param word, a string\n # @return a boolean\n # 3:42\n def exist(self, board, word):\n visited = {}\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.getWords(board, word, i, j, visited):\n return True\n \n return False\n \n def getWords(self, board, word, i, j, visited, pos = 0):\n if pos == len(word):\n return True\n \n if i < 0 or i == len(board) or j < 0 or j == len(board[0]) or visited.get((i, j)) or word[pos] != board[i][j]:\n return False\n \n visited[(i, j)] = True\n res = self.getWords(board, word, i, j + 1, visited, pos + 1) \\\n or self.getWords(board, word, i, j - 1, visited, pos + 1) \\\n or self.getWords(board, word, i + 1, j, visited, pos + 1) \\\n or self.getWords(board, word, i - 1, j, visited, pos + 1)\n visited[(i, j)] = False\n \n return res
51
2
['Depth-First Search', 'Python']
9
word-search
Iterative Python Solution
iterative-python-solution-by-youngjinsu-6xyy
seems the solutions are missing iterative approach.\nWe use stack to do dfs and also keep backtrack state to remove coordinates.\nThe idea is that after we visi
youngjinsu
NORMAL
2018-05-15T09:27:44.817740+00:00
2018-09-01T22:50:52.446188+00:00
4,428
false
seems the solutions are missing iterative approach.\nWe use stack to do dfs and also keep `backtrack` state to remove coordinates.\nThe idea is that after we visit a node, we add a backtracking node to remove the node if we ever come back to the current stack level.\n\n```\nclass Solution(object):\n def neighbors(self, board, r, c):\n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]\n nbs = []\n for d in directions:\n nr = r + d[0]\n nc = c + d[1]\n if (0 <= nr < len(board)) and (0 <= nc < len(board[nr])):\n nbs.append((nr, nc))\n return nbs\n \n def exist(self, board, word):\n """\n :type board: List[List[str]]\n :type word: str\n :rtype: bool\n """\n q = list()\n\t\t\t\t\n for r in range(len(board)): # find starting points\n for c in range(len(board[r])):\n if board[r][c] == word[0]:\n q.append((r, c))\n \n for (r, c) in q:\n visited = set()\n stack = list()\n stack.append((r, c, 0, False)) # regular forward moving node\n while stack:\n cr, cc, i, backtrack = stack.pop()\n if backtrack:\n visited.remove((cr, cc))\n continue\n \n visited.add((cr, cc))\n stack.append((cr, cc, i, True)) # add backtracking node\n if i == (len(word) - 1):\n return True\n \n for nr, nc in self.neighbors(board, cr, cc):\n if (nr, nc) in visited:\n continue\n if board[nr][nc] == word[i + 1]:\n stack.append((nr, nc, i + 1, False)) # forward-moving node\n \n return False\n```
48
0
[]
10
word-search
Clean JavaScript solution
clean-javascript-solution-by-hongbo-miao-713r
Time O(mn * 4^l), l = word.length\nSpace O(mn + l)\n\njs\nconst exist = (board, word) => {\n if (board.length === 0) return false;\n\n const h = board.length;
hongbo-miao
NORMAL
2018-05-23T10:12:56.065321+00:00
2020-09-02T15:45:48.566239+00:00
9,208
false
Time O(mn * 4^l), l = word.length\nSpace O(mn + l)\n\n```js\nconst exist = (board, word) => {\n if (board.length === 0) return false;\n\n const h = board.length;\n const w = board[0].length;\n const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];\n\n const go = (x, y, k) => {\n if (board[x][y] !== word[k]) return false;\n if (k === word.length - 1) return true;\n\n board[x][y] = \'*\'; // mark as visited\n for (const [dx, dy] of dirs) {\n const i = x + dx;\n const j = y + dy;\n if (i >= 0 && i < h && j >= 0 && j < w) {\n if (go(i, j, k + 1)) return true;\n }\n }\n board[x][y] = word[k]; // reset\n return false;\n };\n\n for (let i = 0; i < h; i++) {\n for (let j = 0; j < w; j++) {\n if (go(i, j, 0)) return true;\n }\n }\n\n return false;\n};\n```\n
45
1
['JavaScript']
11
word-search
easily explained with visualization 😎| C++✔ | Java✔|Python✔|
easily-explained-with-visualization-c-ja-e457
If you find it helpful please upvote it \uD83D\uDE3F\uD83D\uDE3F\n\n---\n\n\nstep 1(from board[0][0] it checks 4 recurtion \n(up,down,left,right) one by one)\n\
Recode_-1
NORMAL
2024-04-03T02:28:09.686868+00:00
2024-04-03T02:59:48.574104+00:00
8,447
false
# If you find it helpful please upvote it \uD83D\uDE3F\uD83D\uDE3F\n\n---\n\n```\nstep 1(from board[0][0] it checks 4 recurtion \n(up,down,left,right) one by one)\n\n```\n\n### Example - \n```\nfrom board[0][0] -> board[1][0](this one)->board[-1][0]\n->board[0][1](got the character)\n```\n\n![1.png](https://assets.leetcode.com/users/images/5add8367-d5a5-4722-8a32-256c5876f309_1712110855.7848887.png)\n```\nstep 2 (board[-1][0] and hence invalid)\n\n```\n![2.png](https://assets.leetcode.com/users/images/4b0f82b6-336f-4525-bedc-91d0f0145856_1712110868.3586597.png)\n\n\n\n```\nstep 3\n\n```\n![3.png](https://assets.leetcode.com/users/images/bc3ba236-145c-4d82-9592-74e875fb64db_1712110877.4977424.png)\n```\nstep 4\n\n```\n\n![4.png](https://assets.leetcode.com/users/images/c8a8910d-3333-4afd-ac96-f50ad843fa01_1712110889.2690933.png)\n\n```\nstep 5 (k = 3 , not 2)\n\n```\n![5.png](https://assets.leetcode.com/users/images/853b6c36-2ec4-4fbf-adef-f22522225aa3_1712110896.5772915.png)\n```\nstep 6\n\n```\n![6.png](https://assets.leetcode.com/users/images/59787d7b-10ea-4b8b-ab6d-01f9831209af_1712110903.520588.png)\n\n```\nstep 7\n\n```\n![7.png](https://assets.leetcode.com/users/images/4536063f-b920-4348-8c7b-2be90077dd72_1712110911.3348813.png)\n# Algo\n1. **Depth-First Search (DFS):**\n - Perform a DFS on the grid starting from each cell.\n\n2. **At Each Cell `(i, j)` in the Grid:**\n - Check if the character at `(i, j)` matches the first character of the word.\n - If it matches:\n - Proceed to search for the remaining characters of the word recursively by exploring adjacent cells.\n - Continue this process until all characters of the word are found or until reaching the end of the grid.\n\n3. **During the DFS:**\n - Use a recursive DFS function that takes the current cell `(i, j)`, the word to search for, and the index of the current character being searched in the word.\n - Update the index to search for the next character in the word as traversing the grid.\n - Backtrack if the character at the current cell does not match the expected character in the word.\n\n4. **If All Characters of the Word Are Found:**\n - Return `true`.\n\n5. **If the Word Is Not Found in the Grid:**\n - Return `false`.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool dfs(int i,int j,int count,vector<vector<char>>& board,string word)\n {\n // if we have found the whole string then count will become (word.length()==count) so return true\n if(word.length()==count) return true;\n \n // check for boundary // curr char is not same with word char\n if(i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j] != word[count])\n return false;\n \n \n \n char temp = board[i][j]; // curr char\n board[i][j] = \' \'; // mark as visited\n \n \n // up , down , left , right (possible moves)\n bool ans = dfs(i-1,j,count+1,board,word) || \n dfs(i+1,j,count+1,board,word) ||\n dfs(i,j-1,count+1,board,word) ||\n dfs(i,j+1,count+1,board,word);\n \n board[i][j] = temp; // make board as it is for the upcoming calls\n return ans;\n }\n \n bool exist(vector<vector<char>>& board, string word) \n {\n int n = board.size(); // rows\n int m = board[0].size(); // cols\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(board[i][j]==word[0] && dfs(i,j,0,board,word)) // whenever we found first letter of word start searching from there\n {\n return true;\n }\n }\n }\n \n return false;\n }\n};\n```\n```java []\nclass Solution {\n public boolean exist(char[][] board, String word) {\n // Depth-First Search (DFS):\n // Perform a DFS on the grid starting from each cell.\n \n // Iterate through each cell in the grid\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n // Start DFS from each cell to search for the word\n if (dfs(board, word, i, j, 0))\n return true; // If the word is found, return true\n }\n }\n // If the word is not found after searching all cells, return false\n return false;\n }\n \n // Depth-First Search (DFS) function to search for the word starting from position (i, j)\n public boolean dfs(char[][] board, String word, int i, int j, int idx) {\n // Check if (i, j) is out of bounds or if the character at (i, j) does not match the next character in the word\n if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(idx))\n return false;\n \n // If idx reaches the end of the word, it means the entire word is found\n if (idx == word.length() - 1)\n return true;\n \n // Temporarily store the current character at (i, j)\n char tmp = board[i][j];\n // Mark the current cell as visited by replacing its character with a special character \'*\'\n board[i][j] = \'*\';\n \n // Recursively search in adjacent cells to find the remaining characters of the word\n boolean res = dfs(board, word, i + 1, j, idx + 1) || dfs(board, word, i - 1, j, idx + 1) ||\n dfs(board, word, i, j + 1, idx + 1) || dfs(board, word, i, j - 1, idx + 1);\n \n // Restore the character at (i, j) to its original value\n board[i][j] = tmp;\n \n return res;\n }\n}\n\n```\n```python []\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n # Depth-First Search (DFS):\n # Perform a DFS on the grid starting from each cell.\n \n # Define the DFS function to search for the word starting from position (i, j)\n def dfs(board, word, i, j, idx):\n # Check if (i, j) is out of bounds or if the character at (i, j) does not match the next character in the word\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] != word[idx]:\n return False\n \n # If idx reaches the end of the word, it means the entire word is found\n if idx == len(word) - 1:\n return True\n \n # Temporarily store the current character at (i, j)\n tmp = board[i][j]\n # Mark the current cell as visited by replacing its character with a special character \'*\'\n board[i][j] = \'*\'\n \n # Recursively search in adjacent cells to find the remaining characters of the word\n res = dfs(board, word, i + 1, j, idx + 1) or dfs(board, word, i - 1, j, idx + 1) \\\n or dfs(board, word, i, j + 1, idx + 1) or dfs(board, word, i, j - 1, idx + 1)\n \n # Restore the character at (i, j) to its original value\n board[i][j] = tmp\n \n return res\n \n # Iterate through each cell in the grid\n for i in range(len(board)):\n for j in range(len(board[0])):\n # Start DFS from each cell to search for the word\n if dfs(board, word, i, j, 0):\n return True # If the word is found, return True\n \n # If the word is not found after searching all cells, return False\n return False\n\n```\n\n```\n\n```
42
0
['Array', 'String', 'Backtracking', 'Matrix', 'Python', 'C++', 'Java', 'Python3']
4
word-search
✅☑️ Best C++ Solution Ever || Backtracking || Matrix || String || One Stop Solution.
best-c-solution-ever-backtracking-matrix-5r14
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can solve this problem using Matrix + Backtracking.\n\n# Approach\n Describe your ap
its_vishal_7575
NORMAL
2023-02-23T19:59:29.698745+00:00
2023-02-23T19:59:29.698786+00:00
4,867
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using Matrix + Backtracking.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the approach by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime Complexity: O(N*M*4^L), where L is the length of the word. And we are searching for the letter N*M times in the worst case. Here 4 in 4^K is because at each level of our decision tree we are making 4 recursive calls which equal 4^K in the worst case.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace Complexity : O(L) : where L is the length of the given word. This space is used for recursion stack.\n\n# Code\n```\n/*\n\n Time Complexity: O(N*M*4^L), where L is the length of the word. And we are searching for the letter N*M\n times in the worst case. Here 4 in 4^K is because at each level of our decision tree we are making 4\n recursive calls which equal 4^K in the worst case.\n\n Space Complexity : O(L) : where L is the length of the given word. This space is used for recursion stack.\n\n Solved using Matrix + Backtracking.\n\n*/\n\nclass Solution {\nprivate:\n bool checkWordPresent(vector<vector<char>>& board, string word, int n, int m, int row, int col, int index){\n if(index == word.size()){\n return true;\n }\n if(row < 0 || col < 0 || row >= n || col >= m || board[row][col] != word[index]){\n return false;\n }\n char temp = board[row][col];\n board[row][col] = \'*\';\n bool ans1 = checkWordPresent(board, word, n, m, row+1, col, index+1);\n bool ans2 = checkWordPresent(board, word, n, m, row, col+1, index+1);\n bool ans3 = checkWordPresent(board, word, n, m, row-1, col, index+1);\n bool ans4 = checkWordPresent(board, word, n, m, row, col-1, index+1);\n board[row][col] = temp;\n return ans1 || ans2 || ans3 || ans4;\n }\npublic:\n bool exist(vector<vector<char>>& board, string word) {\n int n = board.size();\n int m = board[0].size();\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(checkWordPresent(board, word, n, m, i, j, 0)){\n return true;\n }\n }\n }\n return false;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg](https://assets.leetcode.com/users/images/0a95fea4-64f4-4502-82aa-41db6d77c05c_1676054939.8270252.jpeg)
41
0
['Array', 'Backtracking', 'Matrix', 'C++']
6
word-search
C++ | Simple and Detailed Explanation
c-simple-and-detailed-explanation-by-jug-umat
Our goal is to find if the word exisits in the matrix or not. We only have to look at the adjacent cells (ignore the diagonal ones).\n\nOne quick look at the pr
juggernaut12
NORMAL
2020-07-21T11:11:20.289247+00:00
2020-07-25T13:35:01.076552+00:00
5,434
false
Our goal is to find if the `word` exisits in the matrix or not. We only have to look at the adjacent cells (ignore the diagonal ones).\n\nOne quick look at the problem can suggest us that we can solve this by Backtracking. Match character-by-character, go ahead and check if the adjacent cells match the next character, and go back if it does not match.\n\nHow should we traverse the matrix efficiently? We need to think of a traversal approach. BFS? DFS? Both can work. But DFS will be better as it immediately checks the next node of the graph and returns if it is not needed after marking it as visited. \n\nFinal solution approach:\n1. For each cell, traverse the entire matrix.\n2. Check if `matrix[i][j] == word[index]`. (we are using `index` to keep track of the characters that we have already checked in the `word` during backtracking.)\n3. If step 2 is true, then check repeat the same process for the adjacent cells and for the next index in the word.\n4. If step 2 is false, then return to the previous state where we received a `true` value and then further check any remaining and unvisited cells.\n\n**Note:** We mark each cell as unvisited after we check all the adjacent possibilities because we might visit that cell again when we start traversing the matrix from a different source cell. You will better understand this when you solve this test case on paper. \n\n`board = [["a","b"],["c","d"]]; word = "cdba"`\n\n**Code:**\n```\nclass Solution {\nprivate:\n int n, m;\n vector<vector<bool>> vis;\n bool dfs(vector<vector<char>> &board, string word, int i, int j, int index)\n {\n if(board[i][j] == word[index])\n {\n vis[i][j] = true;\n if(index == word.length() - 1)\n return true;\n if(i-1 >= 0 && vis[i-1][j] == false)\n if(dfs(board, word, i-1, j, index+1))\n return true;\n if(i+1 < n && vis[i+1][j] == false)\n if(dfs(board, word, i+1, j, index+1))\n return true;\n if(j-1 >= 0 && vis[i][j-1] == false)\n if(dfs(board, word, i, j-1, index+1))\n return true;\n if(j+1 < m && vis[i][j+1] == false)\n if(dfs(board, word, i, j+1, index+1))\n return true;\n vis[i][j] = false;\n return false;\n }\n return false;\n }\npublic:\n bool exist(vector<vector<char>>& board, string word) {\n n = board.size();\n m = board[0].size();\n vis = vector<vector<bool>>(n, vector<bool>(m, false));\n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++)\n {\n if(dfs(board, word, i, j, 0))\n return true;\n }\n return false;\n }\n};\n```\n\nI hope this helps! If you need a clarification, please post it in the comments section.\n\nIf you liked my explanation, then would you be so kind as to upvote this post? It gives me motivation to explain difficult problems in a simple manner.
40
0
['Backtracking', 'Depth-First Search', 'Recursion', 'C']
11
word-search
🥪JavaScript Recursive Solution w/ Explanation
javascript-recursive-solution-w-explanat-8u8k
The idea\nSince it\'s obvious that there will be a lot of repetitive work, such as checking up, down, left, right for lots of characters, we can use recusion to
aminick
NORMAL
2019-10-20T03:41:10.464021+00:00
2019-10-20T03:41:10.464078+00:00
4,443
false
#### The idea\nSince it\'s obvious that there will be a lot of repetitive work, such as checking up, down, left, right for lots of characters, we can use recusion to simplify our code. \nOur base case will need to check:\n1. are we getting out of boundary? if yes, get out.\n2. are we getting a wrong character? If yes, get out.\n3. did we find every character from the work? If yes, great, we have found this word.\nOtherwise keep exploring characters for all directions.\n\n``` javascript\n/**\n * @param {character[][]} board\n * @param {string} word\n * @return {boolean}\n */\nvar exist = function(board, word) {\n let result = false;\n var check = function(r, c, i) {\n if (!result) {\n if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return; // out of boundary\n if (board[r][c] != word[i]) return; // wrong character\n if (i == word.length - 1) { // got to the end means we found a correct path\n result = true;\n return;\n }\n board[r][c] = null; // mark our path so we dont go back and forth\n\t\t\t// try all directions\n check(r+1,c,i+1)\n check(r-1,c,i+1)\n check(r,c+1,i+1)\n check(r,c-1,i+1)\n board[r][c] = word[i] // reset our board , very important\n }\n }\n\n for (let i=0;i<board.length;i++) {\n for (let j=0;j<board[0].length;j++) {\n if (board[i][j] == word[0]) {\n check(i, j, 0)\n if (result) return result;\n }\n }\n }\n \n return result;\n};\n```
40
0
['JavaScript']
3
word-search
✅ C++ || Bakctracking dfs || Easiest Solution with explanation || Beginner Friendly
c-bakctracking-dfs-easiest-solution-with-aspv
Approach\n\n This is a very popular backtracking problem and is many times asked in faang interviews , although its not that difficult!!!\n --
99NotOut_half_dead
NORMAL
2021-10-07T08:02:05.733952+00:00
2021-10-07T08:02:05.733987+00:00
2,754
false
# ***Approach***\n```\n This is a very popular backtracking problem and is many times asked in faang interviews , although its not that difficult!!!\n ------------------------------------------------------------------------------------- \n Let\'s understand the problem statement first!!!\n we are given a matrix of (m x n) and we are required to check whether given word\n exists in matrix or not!!!\n NOTE : we can move in four directions(UP , DOWN , LEFT , RIGHT)\n ------------------------------------------------------------------------------------- \n Solution :\n As the word in matrix can start at any position so we have to check for all\n positions whether each position can be a starting point!!\n \n Now the logic is simple for every call we have index variable which shows how\n much chars of word are already found in current dfs call \n if at any point we found a mismatch between word[index] and baord[x][y] then that branch becomes invalid for us\n \n We use backtracking to make sure that each position/block of matrix \n is visited once in a branch!!![important][visited check]\n```\n# ***Code***\n ```\nclass Solution {\npublic:\n bool exist(vector<vector<char>> &board, string word) {\n // checking for all positions\n for(int i = 0 ; i < board.size() ; ++i)\n for(int j = 0 ; j < board[0].size() ; ++j)\n if(dfs(0 , i , j , board , word))\n return true;\n return false;\n }\n bool dfs(int index , int x , int y , vector<vector<char>> &board , string &word)\n {\n if(index == word.size()) // word exists in matrix\n return true;\n \n if(x < 0 or y < 0 or x >= board.size() or y >= board[0].size() or board[x][y] == \'.\') // boundary check + visited check\n return false;\n \n if(board[x][y] != word[index])\n return false;\n \n char temp = board[x][y];\n board[x][y] = \'.\'; // marking it visited\n \n // Move in 4 directions[UP , DOWN , LEFT , RIGHT]\n if(dfs(index + 1 , x - 1 , y , board , word) or dfs(index + 1 , x + 1 , y , board , word) or dfs(index + 1 , x , y - 1 , board , word) or dfs(index + 1 , x , y + 1 , board , word))\n return true;\n \n board[x][y] = temp; // backtrack step\n return false;\n \n }\n \n};\n```\n# ***If you liked the Solution , Give it an Upvote :)***
39
5
['Backtracking', 'C']
8
word-search
Java | Backtracking template | Explained
java-backtracking-template-explained-by-81yj9
T/S: O(n * (4 ^ w))/O(n), where n is number of cells and w is word length.\nTo avoid confusion, T: O(r * c * (4 ^ w)), where r x c are the dimensions of the boa
prashant404
NORMAL
2019-08-02T20:50:58.079626+00:00
2024-05-14T19:03:33.440395+00:00
8,523
false
**T/S:** O(n * (4 ^ w))/O(n), where n is number of cells and w is word length.\nTo avoid confusion, T: O(r * c * (4 ^ w)), where r x c are the dimensions of the board.\n```\nprivate static final int[][] DIRS = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n\npublic boolean exist(char[][] board, String word) {\n\tfor (var i = 0; i < board.length; i++)\n\t\tfor (var j = 0; j < board[0].length; j++)\n\t\t\tif ((board[i][j] == word.charAt(0)) && exist(board, i, j, 0, word))\n\t\t\t\treturn true;\n\treturn false;\n}\n\n// backtracking template: for each choice: choose-explore-unchoose\nprivate boolean exist(char[][] board, int i, int j, int count, String word) {\n\tif (count == word.length())\n\t\treturn true;\n\tif (i == -1 || i == board.length || j == -1 || j == board[0].length || board[i][j] != word.charAt(count))\n\t\treturn false;\n\t\n\t// choose\n\tvar temp = board[i][j];\n\tboard[i][j] = \' \';\n\tvar found = false;\n\t\n\t// explore\n\tfor (var dir : DIRS)\n\t\tif (exist(board, i + dir[0], j + dir[1], count + 1, word)) {\n\t\t\tfound = true;\n\t\t\tbreak;\n\t\t}\n\n\t// unchoose\n\tboard[i][j] = temp;\n\treturn found;\n}\n```\n\nSame solution using stream\n```\nprivate boolean existStream(char[][] board, String word) {\n\treturn IntStream.range(0, board.length)\n\t\t\t\t\t.anyMatch(i -> IntStream.range(0, board[0].length)\n\t\t\t\t\t\t\t\t\t\t\t.anyMatch(j -> (board[i][j] == word.charAt(0)) && exist(board, i, j, 0, word))\n\t\t\t);\n}\n```\n
39
7
['Backtracking', 'Depth-First Search', 'Java']
11
word-search
Exploring Words: Solving the Grid Word Search Problem with DFS Algorithm
exploring-words-solving-the-grid-word-se-bhou
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires us to find whether a given word can be constructed from the charac
Rare_Zawad
NORMAL
2023-02-25T09:48:58.331283+00:00
2023-02-25T09:48:58.331329+00:00
5,040
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to find whether a given word can be constructed from the characters of the given grid such that adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. The problem can be solved using the Depth First Search (DFS) algorithm. The DFS algorithm works by exploring as far as possible along each branch before backtracking. It is well-suited for problems that require searching through all possible paths.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can approach the problem using the DFS algorithm. We start by iterating through each cell in the grid. For each cell, we check whether the current cell matches the first character of the given word. If the current cell matches the first character of the word, we start a DFS search from that cell, looking for the rest of the characters in the word.\n\nFor each DFS search, we explore all four directions, i.e., up, down, left, and right, to find the next character in the word. We mark the current cell as visited to ensure that we do not use the same cell more than once. If we find the entire word, we return True, else we continue the search from the next unvisited cell.\n\nWe need to keep track of the visited cells to ensure that we do not use the same cell more than once. To mark a cell as visited, we can replace the character in the cell with a special character, such as \'/\'. After completing the DFS search, we can restore the original value of the cell.\n# Complexity\n- Time complexity: The time complexity of the DFS algorithm is proportional to the number of cells in the grid, i.e., O(mn), where m is the number of rows and n is the number of columns. In the worst case, we may have to explore all possible paths to find the word. For each cell, we explore at most four directions, so the time complexity of the DFS search is O(4^k), where k is the length of the word. Therefore, the overall time complexity of the algorithm is O(mn*4^k).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: The space complexity of the algorithm is O(k), where k is the length of the word. This is the space required to store the recursive stack during the DFS search.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n def dfs(i: int, j: int, k: int) -> bool:\n if k == len(word):\n return True\n if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[k]:\n return False\n temp, board[i][j] = board[i][j], \'/\'\n res = dfs(i+1, j, k+1) or dfs(i-1, j, k+1) or dfs(i, j+1, k+1) or dfs(i, j-1, k+1)\n board[i][j] = temp\n return res\n \n m, n = len(board), len(board[0])\n for i in range(m):\n for j in range(n):\n if dfs(i, j, 0):\n return True\n return False\n\n```\n\n# Code Explanation \n\nThis is a Python implementation of the depth-first search algorithm to find if a word exists in a given board of characters.\n\nThe `exist` method takes in two parameters, `board` and `word`, which are the 2D list of characters representing the board and the string representing the word to find, respectively. The method returns a boolean value, `True` if the word exists in the board, and `False` otherwise.\n\nThe algorithm uses a helper function `dfs` to search for the word starting from a given position in the board. The `dfs` function takes in three parameters, `i`, `j`, and `k`, which are the row and column indices of the current position in the board and the index of the current character in the word, respectively. The function returns a boolean value, `True` if the word can be formed starting from this position, and `False` otherwise.\n\nThe `dfs` function first checks if the end of the word has been reached, in which case it returns `True`. If the current position is out of the board or does not match the current character in the word, the function returns `False`.\n\nIf the current position matches the current character in the word, the function temporarily changes the character at the current position to `\'/\'` to mark it as visited and prevent revisiting it in the search. It then recursively calls itself with the adjacent positions (up, down, left, and right) and the next index in the word. If any of the recursive calls returns `True`, the function returns `True` as well.\n\nAfter the search from the current position is finished, the function restores the original character at the current position and returns the final result.\n\nThe `exist` function first gets the dimensions of the board using the `len` function. It then iterates through each cell in the board using nested loops. For each cell, it calls the `dfs` function starting from that position with the first character in the word. If `dfs` returns `True`, the function immediately returns `True` as well since the word has been found. If no word is found after iterating through all cells, the function returns `False`.
37
0
['Array', 'Backtracking', 'Depth-First Search', 'Matrix', 'Python3']
2
word-search
Python simple dfs solution
python-simple-dfs-solution-by-sadida-8iui
def exist(self, board, word):\n if not word:\n return True\n if not board:\n return False\n for i in range(len(board)
sadida
NORMAL
2015-04-20T14:19:15+00:00
2018-10-04T20:43:40.841951+00:00
21,388
false
def exist(self, board, word):\n if not word:\n return True\n if not board:\n return False\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.exist_helper(board, word, i, j):\n return True\n return False\n \n def exist_helper(self, board, word, i, j):\n if board[i][j] == word[0]:\n if not word[1:]:\n return True\n board[i][j] = " " # indicate used cell\n # check all adjacent cells\n if i > 0 and self.exist_helper(board, word[1:], i-1, j):\n return True\n if i < len(board)-1 and self.exist_helper(board, word[1:], i+1, j):\n return True\n if j > 0 and self.exist_helper(board, word[1:], i, j-1):\n return True\n if j < len(board[0])-1 and self.exist_helper(board, word[1:], i, j+1):\n return True\n board[i][j] = word[0] # update the cell to its original value\n return False\n else:\n return False
37
0
['Depth-First Search', 'Python']
6
word-search
Java DFS solution, beats 97.64%
java-dfs-solution-beats-9764-by-kkklll-ggsu
public class Solution {\n public boolean exist(char[][] board, String word) {\n if (word == null || word.length() == 0) {\n ret
kkklll
NORMAL
2016-05-13T21:16:17+00:00
2018-10-25T00:31:05.352920+00:00
18,393
false
public class Solution {\n public boolean exist(char[][] board, String word) {\n if (word == null || word.length() == 0) {\n return true;\n }\n char[] chs = word.toCharArray();\n for (int i = 0; i < board.length; i++) {\n for (int j = 0; j < board[0].length; j++) {\n if(dfs(board, chs, 0, i, j)) {\n return true;\n }\n }\n }\n return false;\n }\n \n private boolean dfs(char[][] board, char[] words, int idx, int x, int y) {\n if (idx == words.length) {\n return true;\n } \n if (x < 0 || x == board.length || y < 0 || y == board[0].length) {\n return false;\n }\n if (board[x][y] != words[idx]) {\n return false;\n }\n board[x][y] ^= 256;\n boolean exist = dfs(board, words, idx + 1, x, y + 1) ||\n dfs(board, words, idx + 1, x, y - 1) || dfs(board, words, idx + 1, x + 1, y) ||\n dfs(board, words, idx + 1, x - 1, y) ;\n board[x][y] ^= 256;\n return exist;\n }\n }
33
4
[]
10
word-search
JavaScript DFS
javascript-dfs-by-moegain-chzi
js\n// Helper Func\nconst isOutOfBound = (board, row, col) => row < 0 || row >= board.length || col < 0 || col >= board[0].length;\n\nconst checkNeighbors = (bo
moegain
NORMAL
2019-11-30T06:42:38.273754+00:00
2019-11-30T06:42:38.273790+00:00
4,776
false
```js\n// Helper Func\nconst isOutOfBound = (board, row, col) => row < 0 || row >= board.length || col < 0 || col >= board[0].length;\n\nconst checkNeighbors = (board, word, row, col) => {\n // Check exit conditions\n if (!word.length) return true;\n if (isOutOfBound(board, row, col) || board[row][col] !== word[0]) return false;\n \n // Save some stuff\n const curChar = board[row][col];\n const newWord = word.substr(1);\n\n board[row][col] = 0; // Disable the current character\n \n // Check if neighbors are fruitful\n const results = checkNeighbors(board, newWord, row + 1, col) ||\n checkNeighbors(board, newWord, row - 1, col) ||\n checkNeighbors(board, newWord, row, col + 1) ||\n checkNeighbors(board, newWord, row, col - 1);\n\n // Enable current character\n board[row][col] = curChar;\n\n return results;\n};\n\n\nvar exist = function(board, word) { \n for (let row = 0; row < board.length; row++) {\n for (let col = 0; col < board[0].length; col++) {\n if (checkNeighbors(board, word, row, col)) return true;\n }\n }\n return false;\n};\n```
31
1
['JavaScript']
2
word-search
[Python3] Backtracking
python3-backtracking-by-zhanweiting-4wxk
\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n for i in range(len(board)):\n for j in range(len(board[i]
zhanweiting
NORMAL
2019-08-21T20:07:19.331060+00:00
2019-08-21T22:18:20.969922+00:00
6,192
false
```\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n for i in range(len(board)):\n for j in range(len(board[i])):\n if self.backtracking(i, j,word,board):\n return True\n return False\n def backtracking(self,i, j,word,board):\n if len(word) == 0:\n return True\n if i < 0 or i >= len(board) or j < 0 or j >= len(board[i]):\n return False\n if board[i][j] == word[0]:\n board[i][j] = "~"\n if self.backtracking(i+1, j, word[1:],board) or self.backtracking(i-1, j, word[1:],board) or self.backtracking(i, j+1, word[1:],board) or self.backtracking( i, j-1, word[1:],board):\n return True\n board[i][j] = word[0]\n return False\n```
30
1
['Backtracking', 'Python', 'Python3']
2
word-search
Java 99% backtracking + pruning
java-99-backtracking-pruning-by-julianzh-p0xd
\nclass Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length;\n int n = board[0].length;\n \n
julianzheng
NORMAL
2021-05-23T08:06:22.943786+00:00
2021-05-23T08:06:22.943842+00:00
2,416
false
```\nclass Solution {\n public boolean exist(char[][] board, String word) {\n int m = board.length;\n int n = board[0].length;\n \n // pruning: case 1: not enough characters in board\n if (word.length() > m * n) return false;\n \n // pruning: case 2: board does not contain characters or enough characters that word contains\n Map<Character, Integer> count = new HashMap<>();\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n int temp = count.getOrDefault(board[i][j], 0);\n count.put(board[i][j], temp + 1);\n }\n }\n \n for (int i = 0; i < word.length(); i++) {\n char c = word.charAt(i);\n if (!count.containsKey(c)) {\n return false;\n } else {\n int temp = count.get(c);\n if (temp == 1) {\n count.remove(c);\n } else {\n count.put(c, temp - 1);\n }\n }\n }\n // Backtracking: if a solution is possible, search for it\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (board[i][j] == word.charAt(0)) {\n boolean[][] marked = new boolean[m][n];\n marked[i][j] = true;\n if (backtracking(board, word, i, j, 1, marked)) return true;\n }\n }\n }\n return false;\n }\n \n private boolean backtracking(char[][] board, String word, int i, int j, int index, boolean[][] marked) {\n if (index == word.length()) return true;\n int m = board.length;\n int n = board[0].length;\n int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n for (int d = 0; d < directions.length; d++) {\n int x = i + directions[d][0];\n int y = j + directions[d][1];\n if (x < 0 || x >= m || y < 0 || y >= n) continue;\n if (board[x][y] == word.charAt(index) && !marked[x][y]) {\n marked[x][y] = true;\n if (backtracking(board, word, x, y, index + 1, marked)) return true;\n marked[x][y] = false;\n }\n }\n return false;\n }\n \n}\n```
29
0
[]
4
word-search
✅ Java, beats 99.3%, DFS, Explained with dry-run on paper
java-beats-993-dfs-explained-with-dry-ru-qg46
If you\'ll like the explanation, do UpVote :)\n### Dry run\n\n\n\t --------------\n\t\t--------------\n\n\nNote: \nDo check Solution 2 as well, which is even mo
karankhara
NORMAL
2022-03-15T03:50:40.242982+00:00
2022-04-07T14:45:52.231640+00:00
3,079
false
If you\'ll like the explanation, do **UpVote** :)\n### Dry run\n\n![image](https://assets.leetcode.com/users/images/e9f9212a-f900-44e0-9d46-69a6ff3245ca_1647315994.8879087.png)\n\t --------------\n\t\t--------------\n\n\n**Note:** \nDo check **Solution 2** as well, which is even more optimized (Runtime: 55 ms, **faster than 99.20%**)\n\t\n### Solution 1 (Very short & Simple code)\n\tclass Solution {\n\t\tpublic boolean exist(char[][] board, String word) {\n\t\t\tint rows = board.length, cols = board[0].length; // length of rows & columns \n\t\t\tif(word.length() == 0){ return true; } // if "word" is empty, we will just return true. \n\t\t\tif(rows * cols < word.length()){ return false; } // if board size (rows*cols) < word length, => word has some character(s) not present in board. So, just return False. This is optimized way as we are avoiding doing DFS search in such test cases. \n\n\t\t\t// Traverse all chars of board\n\t\t\tfor(int r = 0; r < rows; r++){\n\t\t\t\tfor(int c = 0; c < cols; c++){\n\t\t\t\t\tif(board[r][c] == word.charAt(0)){ // keep iterating until we don\'t find first character of "word"\n\t\t\t\t\t\tboolean isFound = dfsBoard(board, new boolean[rows][cols], r, c, word, 0); // call DFS or recursion\n\t\t\t\t\t\tif(isFound){ return true; }\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false; // if we traveresed all chars of board, it means we did not find all chars of word. so return false\n\t\t}\n\t\t// ----------------------------------------------------------------------------------------------------------------------------------------------- //\n\t\tpublic boolean dfsBoard(char[][] board, boolean[][] visitedBoard, int row, int col, String word, int wordInd) { \t\t\t\n\t\t\tif( (row < 0 || row >= board.length) || (col < 0 || col >= board[0].length) || board[row][col] != word.charAt(wordInd) ){\n\t\t\t\treturn false; // return false, if: a) row or col goes out of bound. b) char in board != char in word \n\t\t\t}\n\t\t\tif(visitedBoard[row][col] ){ return false; } // this element already visited, so don\'t do DFS on this\n\t\t\tif(wordInd == word.length() - 1){ return true; }\n\t\t\tvisitedBoard[row][col] = true; // mark it as visited now \n\t\t\t\t\n\t\t\tif( dfsBoard(board, visitedBoard, row, col-1, word, wordInd + 1) ){ return true; } // DFS on Left\n\t\t\tif( dfsBoard(board, visitedBoard, row, col+1, word, wordInd + 1) ){ return true; } // DFS on Right\n\t\t\tif( dfsBoard(board, visitedBoard, row-1, col, word, wordInd + 1) ){ return true; } // DFS on ABove\n\t\t\tif( dfsBoard(board, visitedBoard, row+1, col, word, wordInd + 1) ){ return true; } // DFS on Below\n\t\t\tvisitedBoard[row][col] = false;\n\t\t\treturn false;\n\t\t}\n\t}\n\n//\n//\n//\n//\n//\n//\n//\n\n### Solution 2 (More Optimized)\nJust added a new method **checkWordCharactersInBoard()**\n\t\n\tclass Solution {\n\t\tpublic boolean exist(char[][] board, String word) {\n\t\t\t// Here, same code as in Solution 1\n\t\t\tif(! checkWordCharactersInBoard(board, rows, cols, word) ){ return false; } // check if board contains all chars of word. \n\t\t\t// Here, same code as in Solution 1\t\t\n\t\t}\n\n\t\t// ----------------------------------------------------------------------------------------------------------------------------------------------- //\n\t\tpublic boolean dfsBoard(char[][] board, boolean[][] visitedBoard, int row, int col, String word, int wordInd) { \n\t\t\t// same code as in Solution 1\n\t\t}\n\n\t\t// ----------------------------------------------------------------------------------------------------------------------------------------------- //\n\t\tpublic boolean checkWordCharactersInBoard(char[][] board, int rows, int cols, String word){ // This method helped reducing Runtime further to only 55ms\n\t\t\tList<Character> wordList = new LinkedList<Character>();\n\t\t\tfor(char ch : word.toCharArray()){ wordList.add(ch); }\n\t\t\tfor(int r = 0; r < rows; r++){\n\t\t\t\tfor(int c = 0; c < cols; c++){\n\t\t\t\t\tchar ch = board[r][c];\n\t\t\t\t\tif(wordList.size() == 0){ return true; }\n\t\t\t\t\tif(wordList.contains(ch) ){ wordList.remove((Character)ch); } \n\t\t\t\t}\n\t\t\t}\n\t\t\tif(wordList.size() == 0){ return true; }\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n//\n//\n//\n//\n//\n//\n//\nYou can talk about Solution 2, if you are asked to optimize further. \n## For coding interviews:\n\t1. You can discuss Solution 1 first, and then optimize using Solution 2 (instead of directly jumpting to optimized solution) in coding interview. \n\nIf you like the explanation, do **UpVote** :)\nIf you need more explanation or, if got even more optimized way, **comment** below.
28
0
['Depth-First Search', 'Java']
5
word-search
Easy to understand || DFS || Backtracking || C++ ✅✅🔥🔥
easy-to-understand-dfs-backtracking-c-by-t1s5
\n\n# Approach\n- Iterate on the each cell in grid and use DFS function.\n- in each iteration the DFS do the following:\n - check on the word[ptr] if not equ
Youssef_2274
NORMAL
2024-04-03T00:52:20.632788+00:00
2024-04-03T00:52:20.632824+00:00
8,809
false
![image.png](https://assets.leetcode.com/users/images/cf7e63fc-e665-44a1-8887-69d7d8b580b1_1712104777.7987192.png)\n\n# Approach\n- Iterate on the each cell in grid and use DFS function.\n- in each iteration the DFS do the following:\n - check on the word[ptr] if not equal, return false and try on another cell.\n - if word[ptr] is equla, increse the ptr by 1 and repeat this operation from the 4 neighbor such (up, down, right, left)\n - remember you must in each operation check if you inside grid or not.\n\n\n# Complexity\n- Time complexity: O(n * m * word Length)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(word Length)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nint dr[]{1,-1,0, 0}; \nint dc[]{0, 0,1,-1,};\nclass Solution {\npublic:\n int n, m;\n vector<vector<char>> _board;\n string _word;\n Solution()\n {\n ios_base::sync_with_stdio(false); \n cin.tie(NULL); \n cout.tie(NULL);\n }\n bool isValid(int r, int c)\n {\n if (r < 0 || r >= n)\n return false;\n if (c < 0 || c >= m)\n return false;\n return true;\n }\n\n bool DFS(int r, int c, int ptr)\n {\n if (ptr == _word.size())\n return true;\n \n if (!isValid(r, c) || _board[r][c] == \'0\' || _word[ptr] != _board[r][c])\n return false;\n char tmp = _board[r][c];\n _board[r][c] = \'0\';\n for (int i = 0; i < 4; ++i)\n {\n if(DFS(r + dr[i], c + dc[i], ptr+1))\n return true;\n }\n _board[r][c] = tmp;\n\n return false;\n }\n\n bool exist(vector<vector<char>>& board, string word) {\n n = board.size(), m = board[0].size();\n _board = board;\n _word = word;\n for (int i = 0; i < n; ++i)\n {\n for (int j = 0; j < m; ++j)\n {\n if (DFS(i, j, 0))\n return true;\n }\n }\n return false;\n }\n\n};\n```
26
3
['Backtracking', 'Depth-First Search', 'C++']
3
word-search
✅ EASY TO UNDERSTAND ☑️
easy-to-understand-by-2005115-plal
PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand
2005115
NORMAL
2024-01-22T14:25:32.787285+00:00
2024-01-22T14:25:32.787311+00:00
2,779
false
# **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/_pratay_nandy_/]()**\n\n# Approach\n\n\nExplanation:\n\n1. **`search` function:**\n - The recursive `search` function explores the board to find a match for the given word starting from the current position `(i, j)`.\n - It returns `true` if the entire word is found, and `false` otherwise.\n - The function explores neighbors in all four directions (up, down, left, right) if the current cell matches the current character of the word.\n\n2. **`exist` function:**\n - The `exist` function iterates over each cell in the board and checks if the word can be formed starting from that cell using the `search` function.\n - It returns `true` if any match is found, indicating that the word exists on the board. Otherwise, it returns `false`.\n\n3. **Marking Visited Cells:**\n - The function marks visited cells with the character `\'#\'` to avoid revisiting the same cell in the recursive exploration.\n\n4. **Backtracking:**\n - Before returning from the `search` function, the original character of the current cell is restored, allowing backtracking.\n\nOverall, the code uses a backtracking approach to explore all possible paths on the board to find a match for the given word. The time complexity depends on the number of cells in the board and the length of the word. In the worst case, it is O(N * M * 4^k), where N and M are the dimensions of the board, and k is the length of the word.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**0(N * M * 4^k)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**0(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n![upvote2.png](https://assets.leetcode.com/users/images/6198d926-527c-42f7-a663-aaf8d62ed44c_1704980133.0159707.png)\n\n\n# Code\n```cpp\nclass Solution {\npublic:\n bool search(int i, int j, int n, int m, vector<vector<char>>& board, int k, string word) {\n if (k == word.size()) return true; // If we have matched all characters in the word, return true\n if (i == n || i < 0 || j < 0 || j == m || board[i][j] != word[k]) {\n return false; // If current cell is out of bounds or does not match the current character in word, return false\n }\n \n char ch = board[i][j]; // Store the current character before exploring neighbors\n board[i][j] = \'#\'; // Mark the current cell as visited to avoid revisiting it\n \n // Explore neighbors in all four directions\n bool op1 = search(i + 1, j, n, m, board, k + 1, word); // Down\n bool op2 = search(i - 1, j, n, m, board, k + 1, word); // Up\n bool op3 = search(i, j + 1, n, m, board, k + 1, word); // Right\n bool op4 = search(i, j - 1, n, m, board, k + 1, word); // Left\n \n board[i][j] = ch; // Restore the original character in the board\n \n return op1 || op2 || op3 || op4; // Return true if any of the recursive calls return true\n }\n\n bool exist(vector<vector<char>>& board, string word) {\n int n = board.size(); // Number of rows in the board\n int m = board[0].size(); // Number of columns in the board\n int k = word.size(); // Length of the target word\n\n // Iterate over each cell in the board\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n // Check if the word can be formed starting from the current cell\n if (search(i, j, n, m, board, 0, word)) {\n return true; // If found, return true\n }\n }\n }\n\n return false; // If no match is found, return false\n }\n};\n```
26
0
['Array', 'Backtracking', 'Matrix', 'C++']
7
word-search
✅ C++ || ✅Using DFS || ✅Comments Added || ✅Easy To Learn
c-using-dfs-comments-added-easy-to-learn-6hqr
\nclass Solution {\npublic:\n bool dfs(int i,int j,int count,vector<vector<char>>& board,string word)\n {\n // if we have found the whole string th
mayanksamadhiya12345
NORMAL
2022-11-24T05:47:44.338845+00:00
2022-11-24T05:47:44.338885+00:00
4,197
false
```\nclass Solution {\npublic:\n bool dfs(int i,int j,int count,vector<vector<char>>& board,string word)\n {\n // if we have found the whole string then count will become (word.length()==count) so return true\n if(word.length()==count) return true;\n \n // check for boundary // curr char is not same with word char\n if(i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j] != word[count])\n return false;\n \n \n \n char temp = board[i][j]; // curr char\n board[i][j] = \' \'; // mark as visited\n \n \n // up , down , left , right (possible moves)\n bool ans = dfs(i-1,j,count+1,board,word) || \n dfs(i+1,j,count+1,board,word) ||\n dfs(i,j-1,count+1,board,word) ||\n dfs(i,j+1,count+1,board,word);\n \n board[i][j] = temp; // make board as it is for the upcoming calls\n return ans;\n }\n \n bool exist(vector<vector<char>>& board, string word) \n {\n int n = board.size(); // rows\n int m = board[0].size(); // cols\n \n for(int i=0;i<n;i++)\n {\n for(int j=0;j<m;j++)\n {\n if(board[i][j]==word[0] && dfs(i,j,0,board,word)) // whenever we found first letter of word start searching from there\n {\n return true;\n }\n }\n }\n \n return false;\n }\n};\n```
25
0
['Depth-First Search', 'Recursion']
3