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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bulls-and-cows | [C++] 4ms Straight forward solution two pass O(N) time | c-4ms-straight-forward-solution-two-pass-wt1y | The idea is simple, if two char is match, add aCnt, otherwise, record it and process bCnt in second pass.\n\n class Solution {\n public:\n // only | moumoutsay | NORMAL | 2015-10-30T20:25:23+00:00 | 2018-09-25T10:40:12.248885+00:00 | 25,878 | false | The idea is simple, if two char is match, add aCnt, otherwise, record it and process bCnt in second pass.\n\n class Solution {\n public:\n // only contains digits \n string getHint(string secret, string guess) {\n int aCnt = 0;\n int bCnt = 0;\n vector<int> sVec(10, 0); // 0 ~ 9 for secret\n vector<int> gVec(10, 0); // 0 ~ 9 for guess \n if (secret.size() != guess.size() || secret.empty()) { return "0A0B"; }\n for (int i = 0; i < secret.size(); ++i) {\n char c1 = secret[i]; char c2 = guess[i];\n if (c1 == c2) {\n ++aCnt; \n } else {\n ++sVec[c1-'0'];\n ++gVec[c2-'0'];\n }\n }\n // count b \n for (int i = 0; i < sVec.size(); ++i) {\n bCnt += min(sVec[i], gVec[i]);\n }\n return to_string(aCnt) + 'A' + to_string(bCnt) + 'B';\n }\n }; | 144 | 5 | [] | 18 |
bulls-and-cows | My 3ms Java solution may help u | my-3ms-java-solution-may-help-u-by-blank-a9ad | public class Solution {\n public String getHint(String secret, String guess) {\n int len = secret.length();\n \t\tint[] secretarr = new int | blankj | NORMAL | 2016-02-28T13:17:49+00:00 | 2018-09-09T01:29:05.470232+00:00 | 13,763 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int len = secret.length();\n \t\tint[] secretarr = new int[10];\n \t\tint[] guessarr = new int[10];\n \t\tint bull = 0, cow = 0;\n \t\tfor (int i = 0; i < len; ++i) {\n \t\t\tif (secret.charAt(i) == guess.charAt(i)) {\n \t\t\t\t++bull;\n \t\t\t} else {\n \t\t\t\t++secretarr[secret.charAt(i) - '0'];\n \t\t\t\t++guessarr[guess.charAt(i) - '0'];\n \t\t\t}\n \t\t}\n \t\tfor (int i = 0; i < 10; ++i) {\n \t\t\tcow += Math.min(secretarr[i], guessarr[i]);\n \t\t}\n \t\treturn "" + bull + "A" + cow + "B";\n }\n } | 108 | 0 | [] | 17 |
bulls-and-cows | Python 3 lines solution | python-3-lines-solution-by-xcv58-y68d | use Counter to count guess and secret and sum their overlap. Then use zip to count A.\n\n s, g = Counter(secret), Counter(guess)\n a = sum(i == j | xcv58 | NORMAL | 2015-10-30T23:09:24+00:00 | 2018-10-19T05:28:37.374434+00:00 | 20,854 | false | use `Counter` to count `guess` and `secret` and sum their overlap. Then use `zip` to count `A`.\n\n s, g = Counter(secret), Counter(guess)\n a = sum(i == j for i, j in zip(secret, guess))\n return '%sA%sB' % (a, sum((s & g).values()) - a) | 105 | 4 | ['Python'] | 22 |
bulls-and-cows | 3 lines in Python | 3-lines-in-python-by-stefanpochmann-1j1l | def getHint(self, secret, guess):\n bulls = sum(map(operator.eq, secret, guess))\n both = sum(min(secret.count(x), guess.count(x)) for x in set(gu | stefanpochmann | NORMAL | 2015-10-30T21:33:43+00:00 | 2018-10-16T03:07:10.116542+00:00 | 13,609 | false | def getHint(self, secret, guess):\n bulls = sum(map(operator.eq, secret, guess))\n both = sum(min(secret.count(x), guess.count(x)) for x in set(guess))\n return \'%dA%dB\' % (bulls, both - bulls) | 89 | 3 | ['Python'] | 21 |
bulls-and-cows | Very easy solution using two arrays | very-easy-solution-using-two-arrays-by-w-it8i | public class Solution {\n public String getHint(String secret, String guess) {\n int temp = 0;\n int bulls = 0;\n int[] nums1 = new int[ | wei130 | NORMAL | 2015-12-30T21:12:58+00:00 | 2015-12-30T21:12:58+00:00 | 9,002 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int temp = 0;\n int bulls = 0;\n int[] nums1 = new int[10];\n int[] nums2 = new int[10];\n for(int i = 0; i < secret.length(); i++){\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n if(s == g){\n bulls++;\n }\n else{\n nums1[s - '0']++;\n nums2[g - '0']++;\n }\n }\n int cows = 0;\n for(int i = 0; i < 10; i++){\n cows += Math.min(nums1[i], nums2[i]);\n }\n String res = bulls + "A" + cows + "B";\n return res;\n }\n} | 57 | 0 | [] | 9 |
bulls-and-cows | [Python] Simple solution with counters, explained | python-simple-solution-with-counters-exp-t8hy | Easy, but interesting problem, because it can be solved in different ways.\n\n1. Let us first evaluate number of bulls B: by definition it is number of places w | dbabichev | NORMAL | 2020-09-10T07:17:42.321743+00:00 | 2020-09-10T07:17:42.321773+00:00 | 4,047 | false | Easy, but interesting problem, because it can be solved in different ways.\n\n1. Let us first evaluate number of bulls `B`: by definition it is number of places with the same digit in `secret` and `guess`: so let us just traverse our strings and count it.\n2. Now, let us evaluate both number of cows and bulls: `B_C`: we need to count each digit in `secret` and in `guess` and choose the smallest of these two numbers. Evaluate sum for each digit.\n3. Finally, number of cows will be `B_C - B`, so we just return return the answer!\n\n**Complexity**: both time and space complexity is `O(1)`. Imagine, that we have not `4` lengths, but `n`, then we have `O(n)` time complexity and `O(10)` space complexity to keep our counters.\n\n```\nclass Solution:\n def getHint(self, secret, guess):\n B = sum([x==y for x,y in zip(secret, guess)])\n\t\tCount_sec = Counter(secret)\n Count_gue = Counter(guess)\n B_C = sum([min(Count_sec[elem], Count_gue[elem]) for elem in Count_sec])\n return str(B) + "A" + str(B_C-B) + "B"\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 55 | 6 | [] | 4 |
bulls-and-cows | C++, one pass, O(N) time, O(1) space | c-one-pass-on-time-o1-space-by-csosmo-pulm | class Solution {\n public:\n string getHint(string secret, string guess) {\n unordered_map<char, int> s_map;\n unordered_map<cha | csosmo | NORMAL | 2015-10-30T21:22:16+00:00 | 2015-10-30T21:22:16+00:00 | 7,054 | false | class Solution {\n public:\n string getHint(string secret, string guess) {\n unordered_map<char, int> s_map;\n unordered_map<char, int> g_map;\n int n = secret.size();\n int A = 0, B = 0;\n for (int i = 0; i < n; i++)\n {\n char s = secret[i], g = guess[i];\n if (s == g)\n A++;\n else\n {\n (s_map[g] > 0) ? s_map[g]--, B++ : g_map[g]++;\n (g_map[s] > 0) ? g_map[s]--, B++ : s_map[s]++; \n }\n }\n return to_string(A) + "A" + to_string(B) + "B";;\n } \n }; | 47 | 3 | ['C++'] | 9 |
bulls-and-cows | Java solution with two buckets | java-solution-with-two-buckets-by-jump12-c5wn | public class Solution {\n public String getHint(String secret, String guess) {\n int bull = 0, cow = 0;\n \n int[] sarr | jump1221 | NORMAL | 2015-11-10T01:54:33+00:00 | 2018-10-07T21:00:24.333006+00:00 | 4,652 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int bull = 0, cow = 0;\n \n int[] sarr = new int[10];\n int[] garr = new int[10];\n \n for(int i = 0; i < secret.length(); i++){\n if(secret.charAt(i) != guess.charAt(i)){\n sarr[secret.charAt(i)-'0']++;\n garr[guess.charAt(i)-'0']++;\n }else{\n bull++;\n }\n }\n \n for(int i = 0; i <= 9; i++){\n cow += Math.min(sarr[i], garr[i]);\n }\n \n return (bull + "A" + cow + "B");\n }\n } | 39 | 2 | ['Java'] | 1 |
bulls-and-cows | Fast and easy to understand Python solution O(n) | fast-and-easy-to-understand-python-solut-bzpy | \nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n\t\t# The main idea is to understand that cow cases contain the bull cases\ | mista2311 | NORMAL | 2020-04-04T18:31:43.515592+00:00 | 2020-04-04T18:31:43.515649+00:00 | 2,805 | false | ```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n\t\t# The main idea is to understand that cow cases contain the bull cases\n\t\t\n\t\t# This loop will take care of "bull" cases\n bull=0\n for i in range(len(secret)):\n bull += int(secret[i] == guess[i])\n \n\t\t# This loop will take care of "cow" cases\n cows=0\n for c in set(secret):\n cows += min(secret.count(c), guess.count(c))\n \n return f"{bull}A{cows-bull}B"\n```\n\nI hope that helps :) | 26 | 2 | ['Python', 'Python3'] | 3 |
bulls-and-cows | JavaScript solution | javascript-solution-by-linfongi-pwgj | function getHint(secret, guess) {\n var map = {};\n var A = 0;\n var B = 0;\n for (var i = 0; i < 10; i++) map[i] = 0;\n for (i = 0; i | linfongi | NORMAL | 2015-12-13T05:15:30+00:00 | 2015-12-13T05:15:30+00:00 | 2,652 | false | function getHint(secret, guess) {\n var map = {};\n var A = 0;\n var B = 0;\n for (var i = 0; i < 10; i++) map[i] = 0;\n for (i = 0; i < secret.length; i++) {\n if (secret[i] === guess[i]) A++;\n else {\n map[secret[i]]++;\n B += map[secret[i]] <= 0 ? 1 : 0;\n map[guess[i]]--;\n B += map[guess[i]] >= 0 ? 1 : 0;\n }\n }\n return A + 'A' + B + 'B';\n } | 25 | 0 | ['JavaScript'] | 0 |
bulls-and-cows | Java solution without hashing, 3ms | java-solution-without-hashing-3ms-by-sky-90hu | public String getHint(String secret, String guess) {\n \n if(secret.length() == 0){return "0A0B";}\n \n int bull = 0;\n int c | skyzhou012 | NORMAL | 2016-03-30T21:39:34+00:00 | 2016-03-30T21:39:34+00:00 | 3,800 | false | public String getHint(String secret, String guess) {\n \n if(secret.length() == 0){return "0A0B";}\n \n int bull = 0;\n int cow = 0;\n int [] result = new int [10];\n \n for(int i = 0;i<secret.length();i++)\n {\n int x = secret.charAt(i) - 48;\n int y = guess.charAt(i) - 48;\n \n if(x == y)\n {\n bull++;\n }\n else\n {\n if(result[x] < 0){cow++;}\n result[x]++;\n \n if(result[y] > 0){cow++;}\n result[y]--;\n }\n }\n \n return bull+"A"+cow+"B";\n \n } | 23 | 0 | ['Java'] | 2 |
bulls-and-cows | PYTHON dict solution | python-dict-solution-by-yiling-imu2 | class Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :r | yiling | NORMAL | 2015-11-23T11:42:50+00:00 | 2015-11-23T11:42:50+00:00 | 3,176 | false | class Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :rtype: str\n """\n d = {}\n bull, cow = 0,0\n \n for index,s in enumerate(secret):\n if guess[index] == s:\n bull += 1\n else:\n d[s] = d.get(s,0) + 1\n \n for index,s in enumerate(secret):\n if (guess[index] != s) & (d.get(guess[index],0) != 0):\n \t cow += 1\n \t d[guess[index]] -= 1\n \t \n return str(bull) + "A" + str(cow) + "B" | 18 | 0 | ['Python'] | 3 |
bulls-and-cows | Python simple solution | python-simple-solution-by-fan50-f880 | class Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :r | fan50 | NORMAL | 2016-03-22T20:50:22+00:00 | 2018-08-23T02:12:21.256274+00:00 | 4,307 | false | class Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :rtype: str\n """\n bulls = 0\n l1, l2 = [0]*10, [0]*10\n nums1, nums2 = map(int, secret), map(int, guess)\n length = len(secret)\n for i in xrange(length):\n if nums1[i] == nums2[i]:\n bulls += 1\n else:\n l1[nums1[i]] += 1\n l2[nums2[i]] += 1\n cows = sum(map(min, zip(l1,l2)))\n return '%dA%dB' % (bulls, cows) | 15 | 0 | [] | 2 |
bulls-and-cows | JAVA | HashMap / Frequency Array | Clean ✅ | java-hashmap-frequency-array-clean-by-so-jo3z | Please Upvote :D\n##### 1. Using HashMap to store character frequency:\n\nclass Solution {\n public String getHint(String secret, String guess) {\n in | sourin_bruh | NORMAL | 2022-10-25T12:52:15.992129+00:00 | 2022-10-25T12:52:15.992168+00:00 | 1,184 | false | ### **Please Upvote** :D\n##### 1. Using HashMap to store character frequency:\n```\nclass Solution {\n public String getHint(String secret, String guess) {\n int bulls = 0, cows = 0;\n\n Map<Character, Integer> secretFreq = new HashMap<>();\n Map<Character, Integer> guessFreq = new HashMap<>();\n\n for (int i = 0; i < secret.length(); i++) {\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n\n if (s == g) bulls++;\n else {\n secretFreq.put(s, secretFreq.getOrDefault(s, 0) + 1);\n guessFreq.put(g, guessFreq.getOrDefault(g, 0) + 1);\n }\n }\n\n for (char c : secretFreq.keySet()) {\n if (guessFreq.containsKey(c)) {\n cows += Math.min(secretFreq.get(c), guessFreq.get(c));\n }\n }\n\n return bulls + "A" + cows + "B";\n }\n}\n\n// TC: O(n), SC: O(n)\n\n```\n##### 2. Using Arrays to store character frequency:\n```\nclass Solution {\n public String getHint(String secret, String guess) {\n int bulls = 0, cows = 0;\n\n int[] secretFreq = new int[10],\n guessFreq = new int[10];\n\n for (int i = 0; i < secret.length(); i++) {\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n\n if (s == g) bulls++;\n else {\n secretFreq[s - \'0\']++;\n guessFreq[g - \'0\']++;\n }\n }\n\n for (int i = 0; i < 10; i++) {\n cows += Math.min(secretFreq[i], guessFreq[i]);\n }\n\n return bulls + "A" + cows + "B";\n }\n}\n\n// TC: O(n), SC: O(1)\n``` | 14 | 0 | ['Array', 'Java'] | 0 |
bulls-and-cows | Easy java solution | easy-java-solution-by-danielfang-yx7q | public class Solution {\n public String getHint(String secret, String guess) {\n int bull = 0, cow = 0;\n int[] array = new int[10];\n \ | danielfang | NORMAL | 2016-01-14T06:25:31+00:00 | 2016-01-14T06:25:31+00:00 | 2,338 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int bull = 0, cow = 0;\n int[] array = new int[10];\n \n for(int i = 0; i < secret.length(); i++) {\n char s = secret.charAt(i);\n char g = guess.charAt(i);\n if(s == g){\n bull++;\n }else {\n if(array[s - '0'] < 0) {\n cow++;\n }\n array[s - '0']++;\n \n if(array[g - '0'] > 0) {\n cow++;\n }\n array[g -'0']--;\n }\n }\n return bull + "A" + cow + "B";\n }\n } | 14 | 0 | [] | 3 |
bulls-and-cows | Clean and Crisp C++ | clean-and-crisp-c-by-vibhoar_bajaj-rwnm | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n unordered_map m;\n int b =0;\n int c=0;\n for(in | Vibhoar_Bajaj | NORMAL | 2022-09-30T17:03:40.879961+00:00 | 2022-09-30T17:03:40.880011+00:00 | 829 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n unordered_map<char, int> m;\n int b =0;\n int c=0;\n for(int i =0;i<secret.size();i++){\n if(secret[i]== guess[i]){\n b++;\n }\n else{\n m[secret[i]]++;\n }\n }\n\n for(int i =0;i<secret.size();i++){\n if(secret[i]!= guess[i]){\n if(m[guess[i]]>0){\n c++;\n m[guess[i]]--;\n }\n }\n }\n string a = to_string(b) + "A" + to_string(c) + "B";\n return a ;\n }\n};\n//upvote pls | 13 | 0 | ['C'] | 1 |
bulls-and-cows | C++ Super Simple Solution | c-super-simple-solution-by-debbiealter-0062 | \nclass Solution {\npublic:\n string getHint(string secret, string guess)\n {\n map<char,int> secretMap, guessMap;\n int bulls = 0, cows = 0 | debbiealter | NORMAL | 2020-09-10T09:23:12.694312+00:00 | 2020-09-10T09:23:33.011902+00:00 | 1,314 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess)\n {\n map<char,int> secretMap, guessMap;\n int bulls = 0, cows = 0;\n \n for (size_t i = 0; i < secret.length(); i++)\n {\n if(secret[i] == guess[i])\n {\n bulls++;\n }\n else\n {\n secretMap[secret[i]]++;\n guessMap[guess[i]]++;\n }\n }\n \n for(auto x: secretMap)\n {\n if (guessMap.find(x.first) != guessMap.end()) \n {\n cows += min(x.second, guessMap[x.first]);\n }\n }\n \n return to_string(bulls) + "A" + to_string(cows) + "B";\n }\n\n};\n``` | 13 | 0 | ['C', 'C++'] | 0 |
bulls-and-cows | Java simple solution O(n) with Video explanation | java-simple-solution-on-with-video-expla-wpfh | \n\n```\nclass Solution {\n \n // O(n) time complexity , O(1) =>Space\n public String getHint(String secret, String guess) {\n int bulls =0;\n | learner18 | NORMAL | 2020-09-10T08:43:33.781189+00:00 | 2020-09-10T08:43:33.781218+00:00 | 554 | false | <iframe width="650" height="450" src="https://www.youtube.com/embed/sEGa8F2pMS8" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n\n```\nclass Solution {\n \n // O(n) time complexity , O(1) =>Space\n public String getHint(String secret, String guess) {\n int bulls =0;\n int cows =0;\n int[] secretFreq =new int[10];\n \n int[] guessFreq =new int[10];\n \n // O(n)\n for(int i=0;i<secret.length();i++){\n char secretChar = secret.charAt(i);\n \n char guessChar = guess.charAt(i);\n \n if(secretChar == guessChar){\n bulls++;\n } else{\n secretFreq[secretChar -\'0\']++;\n \n guessFreq[guessChar -\'0\']++;\n }\n }\n \n // O(1)\n for(int i=0;i<10;i++){\n cows += Math.min(secretFreq[i], guessFreq[i]);\n }\n \n return bulls +"A"+ cows +"B";\n }\n} | 11 | 3 | [] | 0 |
bulls-and-cows | My Concise JAVA Solution | my-concise-java-solution-by-coderoath-7yhu | public String getHint(String secret, String guess) {\n int a=0,b=0;\n int[] digits=new int[10];\n for(int i=0;i<secret.length();i++){\n | coderoath | NORMAL | 2015-10-31T08:22:40+00:00 | 2015-10-31T08:22:40+00:00 | 2,511 | false | public String getHint(String secret, String guess) {\n int a=0,b=0;\n int[] digits=new int[10];\n for(int i=0;i<secret.length();i++){\n if(secret.charAt(i)==guess.charAt(i)) a++;\n else{\n if(++digits[secret.charAt(i)-'0']<=0) b++;\n if(--digits[guess.charAt(i)-'0']>=0) b++;\n }\n }\n return a+"A"+b+"B";\n } | 11 | 1 | ['Java'] | 2 |
bulls-and-cows | ✔️ 8ms solution | C++ | 8ms-solution-c-by-coding_menance-gmm4 | Here is the code for C++ along with explanation in comments:\n\n# Code\n\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n | coding_menance | NORMAL | 2022-11-04T18:13:39.624589+00:00 | 2022-11-04T18:13:39.624628+00:00 | 1,291 | false | Here is the code for C++ along with explanation in comments:\n\n# Code\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n vector<int> cowsS(10, 0);\n vector<int> cowsG(10, 0);\n\n int bulls{0}, cows{0};\n for (int i{0}; i<secret.size(); ++i) {\n // if the numbers in the positions match then it\'s a bull\n if (secret[i]==guess[i]) bulls++;\n else {\n // we add bulls corresponding to the numbers (eg, if secret[i]=5)\n // ascii of 5 is 53 and ascii of 0 is 48 and therefore 53-48 = 5 which is the poition given in secret[i]\n cowsS[secret[i]-\'0\']++;\n cowsG[guess[i]-\'0\']++;\n }\n }\n\n for (int i{0}; i<cowsG.size(); ++i) {\n // let\'s day cowsS[4]=5, it means that \'4\' is present 5 times in secret\n // same goes for cowsS. The minimum of either gives the number of matches (the extra ones can\'t match)\n cows+=min(cowsG[i], cowsS[i]);\n }\n\n // to_string converts ascii to integer. (eg., \'5\' to 5)\n return to_string(bulls)+\'A\'+to_string(cows)+\'B\';\n\n }\n};\n```\n\n*Upvote solution if the explanation helped you understand* \uD83D\uDE04\n\n*Happy coding!* | 10 | 0 | ['String', 'C++'] | 1 |
bulls-and-cows | ✔️ Python O(n) Solution Using Hashmap with Explanation | 99% Faster 🔥 | python-on-solution-using-hashmap-with-ex-7qgf | \uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D\n\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n # Di | pniraj657 | NORMAL | 2022-10-20T04:51:02.734201+00:00 | 2022-10-31T05:29:41.665863+00:00 | 2,241 | false | **\uD83D\uDD3C IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE \uD83D\uDC4D**\n\n```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n # Dictionary for Lookup\n lookup = Counter(secret)\n \n x, y = 0, 0\n \n # First finding numbers which are at correct position and updating x\n for i in range(len(guess)):\n if secret[i] == guess[i]:\n x+=1\n lookup[secret[i]]-=1\n \n # Finding numbers which are present in secret but not at correct position \n for i in range(len(guess)):\n if guess[i] in lookup and secret[i] != guess[i] and lookup[guess[i]]>0:\n y+=1\n lookup[guess[i]]-=1\n \n\t\t# The reason for using two for loop is in this problem we have \n\t\t# to give first priority to number which are at correct position,\n\t\t# Therefore we are first updating x value\n\t\t\n return "{}A{}B".format(x, y)\n```\n**If you\'re interested in learning Python, check out my blog. https://www.python-techs.com/** | 9 | 0 | ['Python', 'Python3'] | 3 |
bulls-and-cows | JavaScript 93.83% one pass | javascript-9383-one-pass-by-shengdade-1bb9 | \n/**\n * @param {string} secret\n * @param {string} guess\n * @return {string}\n */\nvar getHint = function(secret, guess) {\n let bull = 0;\n let cow = 0;\n | shengdade | NORMAL | 2020-01-28T01:54:29.154307+00:00 | 2020-01-28T01:54:29.154361+00:00 | 1,258 | false | ```\n/**\n * @param {string} secret\n * @param {string} guess\n * @return {string}\n */\nvar getHint = function(secret, guess) {\n let bull = 0;\n let cow = 0;\n const map = {};\n for (let i = 0; i < secret.length; i++) {\n const s = secret.charAt(i);\n const g = guess.charAt(i);\n if (s === g) {\n bull++;\n } else {\n if (map[s] < 0) cow++;\n if (map[g] > 0) cow++;\n map[s] = parseInt(map[s] || \'0\') + 1;\n map[g] = parseInt(map[g] || \'0\') - 1;\n }\n }\n return `${bull}A${cow}B`;\n};\n``` | 9 | 0 | ['JavaScript'] | 0 |
bulls-and-cows | 4ms C++ One Array Clean Solution | 4ms-c-one-array-clean-solution-by-spanla-w741 | class Solution {\n public:\n string getHint(string secret, string guess) {\n int map[10] = {0};\n int a = 0, b = 0;\n | spanlabs | NORMAL | 2015-11-09T23:53:44+00:00 | 2015-11-09T23:53:44+00:00 | 818 | false | class Solution {\n public:\n string getHint(string secret, string guess) {\n int map[10] = {0};\n int a = 0, b = 0;\n for (int i = 0; i < guess.size(); ++i) {\n if (guess[i] == secret[i]) ++a;\n ++map[guess[i] - '0'];\n }\n for (int i = 0; i < secret.size(); ++i) {\n if (map[secret[i] - '0']-- > 0) ++b;\n }\n return to_string(a) + "A" + to_string(b - a) + "B";\n }\n };\n\n`a` stores "bulls" while `b` stores sum of "bulls" and "cows". <br>\nWe only need to build one hash map for "guess". First loop is to build hash map as well as to find "bulls". The second one is to find all "guess" numbers existing in "secret". When there is a match, we reduce the value for this number to handle situation like ("11" "10"). <br>\nTime: O(n) Space: O(1) | 9 | 0 | [] | 0 |
bulls-and-cows | Java without hash( 3 ms) | java-without-hash-3-ms-by-skoy12-muj8 | public String getHint(String secret, String guess) {\n char[] s = secret.toCharArray();\n char[] g = guess.toCharArray();\n int a = 0, b = | skoy12 | NORMAL | 2016-05-31T02:10:07+00:00 | 2016-05-31T02:10:07+00:00 | 937 | false | public String getHint(String secret, String guess) {\n char[] s = secret.toCharArray();\n char[] g = guess.toCharArray();\n int a = 0, b = 0;\n int[] count = new int[10];\n for(int i = 0; i < s.length; i++){\n if(s[i] == g[i]) a++;\n else{\n if(count[s[i] - '0']++ < 0) b++;\n if(count[g[i] - '0']-- > 0) b++;\n }\n }\n return a+"A"+b+"B";\n } | 9 | 0 | [] | 0 |
bulls-and-cows | java simple solution beats 100% in time | java-simple-solution-beats-100-in-time-b-7y3u | \nclass Solution {\n public String getHint(String secret, String guess) {\n int bull = 0;\n int[] countsSecret = new int[10];\n int[] co | jasonhey93 | NORMAL | 2020-02-18T16:23:37.768181+00:00 | 2020-02-18T16:23:37.768215+00:00 | 817 | false | ```\nclass Solution {\n public String getHint(String secret, String guess) {\n int bull = 0;\n int[] countsSecret = new int[10];\n int[] countsGuess = new int[10];\n for (int i = 0; i < secret.length(); i++) {\n char a = secret.charAt(i);\n char b = guess.charAt(i);\n if (a == b)\n bull ++;\n else {\n countsSecret[a-\'0\'] ++;\n countsGuess[b-\'0\'] ++;\n }\n }\n int count = 0;\n for (int i = 0; i < 10; i++)\n count += Math.min(countsSecret[i], countsGuess[i]);\n StringBuilder sb = new StringBuilder();\n sb.append(bull).append("A").append(count).append("B");\n return sb.toString();\n }\n}\n``` | 8 | 0 | ['Java'] | 1 |
bulls-and-cows | a few solutions | a-few-solutions-by-claytonjwong-xueg | For each ith digit in A and B, there are 2 use cases to consider:\n Case 1: if it\'s the same digit, then increment bull for the digit\n Case 2: if it\'s not th | claytonjwong | NORMAL | 2019-10-12T00:53:49.414796+00:00 | 2023-01-01T23:53:35.822214+00:00 | 312 | false | For each `i`<sup>th</sup> digit in `A` and `B`, there are 2 use cases to consider:\n* **Case 1:** if it\'s the same digit, then increment `bull` for the digit\n* **Case 2:** if it\'s *not* the same digit, then increment the digit count for `A` and `B` via `\uD83D\uDDFA` maps `first` and `second` correspondingly\n\nThen `cow` is the accumulated minimum count of each digit in `\uD83D\uDDFA` maps `first` and `second`.\n\n---\n\n*Javascript*\n```\nlet getHint = (A, B, bull = 0, cow = 0) => {\n let first = Array(10).fill(0), \n second = Array(10).fill(0);\n for (let i = 0; i < A.length; ++i)\n if (A[i] == B[i])\n ++bull; // case 1: same digit, increment bull\n else\n ++first[A[i]], // case 2: diff digit, increment corresponding digit count\n\t\t\t++second[B[i]];\n for (let i = 0; i < 10; ++i)\n cow += Math.min(first[i], second[i]);\n return `${bull}A${cow}B`;\n};\n```\n\n*Python3*\n```\nclass Solution:\n def getHint(self, A: str, B: str, bull = 0, cow = 0) -> str:\n A = [int(c) for c in A]\n B = [int(c) for c in B]\n first, second = [0] * 10, [0] * 10\n for i in range(len(A)):\n if A[i] == B[i]:\n bull += 1 # case 1: same digit, increment bull\n else:\n first[A[i]] += 1 # case 2: diff digit, increment corresponding digit count\n second[B[i]] += 1\n for i in range(10):\n cow += min(first[i], second[i])\n return f\'{bull}A{cow}B\'\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VI = vector<int>;\n string getHint(string A, string B, int bull = 0, int cow = 0) {\n VI first(10), second(10);\n for (auto i{ 0 }; i < A.size(); ++i)\n if (A[i] == B[i])\n ++bull; // case 1: same digit, increment bull\n else\n ++first[A[i] - \'0\'], // case 2: diff digit, increment corresponding digit count\n\t\t\t\t++second[B[i] - \'0\'];\n for (auto i{ 0 }; i < 10; ++i)\n cow += min(first[i], second[i]);\n ostringstream hint;\n hint << bull << "A"\n << cow << "B";\n return hint.str();\n }\n};\n``` | 8 | 0 | [] | 1 |
bulls-and-cows | Python solution using a Counter | python-solution-using-a-counter-by-jddym-xy50 | I think the most tricky part is just to understand what cows mean... \n\n class Solution(object):\n def getHint(self, secret, guess):\n """\n | jddymx | NORMAL | 2015-11-07T08:07:17+00:00 | 2015-11-07T08:07:17+00:00 | 1,068 | false | I think the most tricky part is just to understand what cows mean... \n\n class Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :rtype: str\n """\n from collections import Counter\n c = Counter(secret)\n bulls, cows = 0,0\n for i in xrange(len(secret)):\n if secret[i]==guess[i]:\n bulls += 1\n c[secret[i]] -= 1\n for i in xrange(len(secret)):\n if secret[i]!=guess[i]:\n if guess[i] in c and c[guess[i]]>0:\n c[guess[i]] -= 1\n cows += 1 \n return str(bulls)+'A'+str(cows)+'B' | 8 | 0 | ['Python'] | 0 |
bulls-and-cows | Java: Beats 100% | java-beats-100-by-deleted_user-by93 | Java: Beats 100%\n\n\n\n# Code\n\nclass Solution {\n public String getHint(String secret, String guess) {\n int secdigs[] = new int[10];\n int | deleted_user | NORMAL | 2024-05-09T11:26:43.356167+00:00 | 2024-05-09T11:26:43.356206+00:00 | 416 | false | Java: Beats 100%\n\n\n\n# Code\n```\nclass Solution {\n public String getHint(String secret, String guess) {\n int secdigs[] = new int[10];\n int guessdigs[] = new int[10];\n int bull = 0, cow = 0;\n\n for(int i = 0; i < secret.length() ; i ++) {\n if(secret.charAt(i) == guess.charAt(i)) {\n bull ++;\n }\n else {\n secdigs[secret.charAt(i) - \'0\'] ++;\n guessdigs[guess.charAt(i) - \'0\'] ++;\n }\n }\n for(int i = 0; i < 10; i ++) {\n int minVal = secdigs[i];\n if(minVal > guessdigs[i]) minVal = guessdigs[i];\n cow += minVal;\n }\n StringBuilder sb = new StringBuilder();\n sb.append(bull).append("A").append(cow).append("B");\n return sb.toString();\n }\n}\n``` | 7 | 0 | ['Java'] | 0 |
bulls-and-cows | [Python] Very simple space O(1) solution without fancy tricks | python-very-simple-space-o1-solution-wit-1joa | It\'s straightforward to calculate bulls - if the characters at the same index are identical in two strings, we add 1 to bulls.\nThe core idea to calculate cows | shanetsui | NORMAL | 2020-05-18T05:17:59.722121+00:00 | 2020-05-18T05:25:59.756507+00:00 | 405 | false | It\'s straightforward to calculate bulls - if the characters at the same index are identical in two strings, we add 1 to bulls.\nThe core idea to calculate cows is to match the rest characters (the ones unmatched in bulls) as much as possible. We calculate it as (\'-\' means minus) :\n\n**cows = characters matched at different index = total number of characters in guess - bulls(i.e. number of characters matched at the same index) - number of unmatched characters**\n\nIt\'s straighforward to get total number of characters in guess and bulls, the only trick part is how to calculate number of unmatched characters. Here\'s how the algorithm works. We maintain a counter on the fly. Whenever the two characters differ (cannot be counted as bulls), we add 1 to secret character\'s count because it can be used to cancel out a character shown up in guess, and subtract 1 from guess character\'s count to do the cancel-out. If there are enough characters in secret to cancel out, the counter remains non-negative. As for the negative values, we know there are character cannot be matched, and the amount of the characters is its absolute value. So the sum of all negative value\'s absolute value is the 3rd term. \n\n```python\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bulls = 0\n cnt = Counter()\n for c1, c2 in zip(secret, guess):\n if c1 == c2:\n bulls += 1\n else:\n cnt[c1] += 1\n cnt[c2] -= 1\n cows = len(secret) - bulls - sum(-i for i in cnt.values() if i < 0)\n return f"{bulls}A{cows}B"\n``` | 7 | 0 | [] | 1 |
bulls-and-cows | 4ms concise c++ solution | 4ms-concise-c-solution-by-liankaohk-swgc | class Solution {\n public:\n string getHint(string secret, string guess) {\n vector<int> s(10, 0); // s[i]: number of occurrences of i in s | liankaohk | NORMAL | 2015-12-30T08:35:07+00:00 | 2015-12-30T08:35:07+00:00 | 1,048 | false | class Solution {\n public:\n string getHint(string secret, string guess) {\n vector<int> s(10, 0); // s[i]: number of occurrences of i in secret\n vector<int> g(10, 0); // g[i]: number of occurrences of i in guess\n int A = 0;\n for(int i = 0; i < secret.size(); ++i){\n if(secret[i] == guess[i])\n ++A;\n s[secret[i] - '0']++;\n g[guess[i] - '0']++;\n }\n int B = -A;\n for(int i = 0; i < 10; ++i){\n B += min(s[i], g[i]);\n }\n return to_string(A) + "A" + to_string(B) + "B";\n }\n }; | 7 | 1 | ['C++'] | 2 |
bulls-and-cows | Easy c++ solution with unordered_map | easy-c-solution-with-unordered_map-by-vo-yzls | string getHint(string secret, string guess) {\n \tunordered_map<char, int> mp;\n \tint n = secret.size(), cA = 0, cB = 0;\n \tfor (int i = 0; i < n; i+ | voka | NORMAL | 2016-05-24T12:30:52+00:00 | 2016-05-24T12:30:52+00:00 | 728 | false | string getHint(string secret, string guess) {\n \tunordered_map<char, int> mp;\n \tint n = secret.size(), cA = 0, cB = 0;\n \tfor (int i = 0; i < n; i++) {\n \t\tif (secret[i] == guess[i]) {\n \t\t\tcA++;\n \t\t\tcontinue;\n \t\t}\n \t\tmp[secret[i]]++;\n \t}\n \tfor (int i = 0; i < n; i++) {\n \t\tif (secret[i] != guess[i] && mp[guess[i]] > 0) {\n \t\t\tmp[guess[i]]--;\n \t\t\tcB++;\n \t\t}\n \t}\n \treturn to_string(cA) + 'A' + to_string(cB) + 'B';\n } | 7 | 0 | [] | 0 |
bulls-and-cows | 299: Time 98.43% and Space 98.71%, Solution with step by step explanation | 299-time-9843-and-space-9871-solution-wi-2w8c | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Define the function getHint that takes two strings secret and guess as | Marlen09 | NORMAL | 2023-02-28T05:06:11.275903+00:00 | 2023-02-28T05:06:11.275954+00:00 | 2,422 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define the function getHint that takes two strings secret and guess as input and returns a string.\n2. Initialize two dictionaries secret_dict and guess_dict to store the frequencies of digits in the secret and guess strings, respectively.\n3. Initialize two variables bulls and cows to 0, to keep track of the number of bulls and cows.\n4. Loop through the length of the secret string and compare each digit in the secret string with the corresponding digit in the guess string.\n5. If the digits are the same, increment the bulls count and decrement the frequency of that digit in both secret_dict and guess_dict.\n6. If the digits are different, check if the current digit in the guess string exists in secret_dict and its frequency is greater than 0. If so, increment the cows count and decrement the frequency of that digit in secret_dict.\n7. Finally, return the formatted hint string as "xAyB", where x is the number of bulls and y is the number of cows.\n\n# Complexity\n- Time complexity:\n98.43%\n\n- Space complexity:\n98.71%\n\n# Code\n```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n secret_dict = {}\n guess_dict = {}\n bulls = 0\n cows = 0\n \n for i in range(len(secret)):\n if secret[i] == guess[i]:\n bulls += 1\n else:\n if secret[i] in guess_dict and guess_dict[secret[i]] > 0:\n cows += 1\n guess_dict[secret[i]] -= 1\n else:\n secret_dict[secret[i]] = secret_dict.get(secret[i], 0) + 1\n if guess[i] in secret_dict and secret_dict[guess[i]] > 0:\n cows += 1\n secret_dict[guess[i]] -= 1\n else:\n guess_dict[guess[i]] = guess_dict.get(guess[i], 0) + 1\n \n return str(bulls) + "A" + str(cows) + "B"\n\n``` | 6 | 0 | ['Hash Table', 'String', 'Counting', 'Python', 'Python3'] | 1 |
bulls-and-cows | Bulls and Cows - O(N) time Clear solution | bulls-and-cows-on-time-clear-solution-by-jshh | \nclass Solution:\n \n def getHint(self, secret, guess):\n \n # char freq map for guests\n\t\t\n freqMap = {}\n \n for | onlyfaang | NORMAL | 2020-09-10T07:14:25.149513+00:00 | 2020-09-10T07:15:02.602148+00:00 | 625 | false | ```\nclass Solution:\n \n def getHint(self, secret, guess):\n \n # char freq map for guests\n\t\t\n freqMap = {}\n \n for num in guess:\n \n if not num in freqMap:\n freqMap[num] = 0\n \n freqMap[num] += 1\n\t\t\t\n\t\t\t\n \n # count bulls\n\t\t\n bulls = 0\n \n for i in range(len(guess)):\n \n if secret[i] == guess[i]:\n bulls += 1\n \n\t\t\t \n \n # count total number of matching chars:\n \n total = 0\n \n for num in secret:\n \n if num in freqMap:\n total += 1\n \n if freqMap[num] == 1:\n del freqMap[num]\n \n else:\n freqMap[num] -= 1\n \n \n # cows = total - bulls\n cows = total - bulls\n \n return str(bulls) + "A" + str(cows) + "B"\n \n \n \n``` | 6 | 1 | [] | 3 |
bulls-and-cows | Solution in Python 3 (beats ~98%) | solution-in-python-3-beats-98-by-junaidm-eott | ```\nfrom collections import Counter\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \ts, g, i = list(secret), list(guess), 0\n | junaidmansuri | NORMAL | 2019-08-04T12:42:58.437542+00:00 | 2019-08-04T12:46:23.996665+00:00 | 1,026 | false | ```\nfrom collections import Counter\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \ts, g, i = list(secret), list(guess), 0\n \twhile i < len(s):\n \t\tif g[i] == s[i]:\n \t\t\tdel s[i], g[i]\n \t\t\ti -= 1\n \t\ti += 1\n \treturn str(len(secret)-len(s))+\'A\'+str(sum((Counter(s)&Counter(g)).values()))+\'B\'\n\t\t\n\t\t\n- Junaid Mansuri | 6 | 1 | ['Python', 'Python3'] | 3 |
bulls-and-cows | Swift solution 40ms | swift-solution-40ms-by-jesen860-zuct | \nclass Solution {\n func getHint(_ secret: String, _ guess: String) -> String {\n var bull = 0\n var cow = 0\n \n let s = Array( | jesen860 | NORMAL | 2018-10-07T15:05:55.557693+00:00 | 2018-10-07T15:05:55.557738+00:00 | 249 | false | ```\nclass Solution {\n func getHint(_ secret: String, _ guess: String) -> String {\n var bull = 0\n var cow = 0\n \n let s = Array(secret)\n let g = Array(guess)\n var num = [Character : Int]()\n \n for i in 0 ..< s.count {\n if s[i] == g[i] {\n bull += 1\n } else {\n if num[s[i], default:0] < 0 {\n cow += 1\n }\n if num[g[i], default:0] > 0 {\n cow += 1\n }\n num[s[i], default:0] += 1\n num[g[i], default:0] -= 1\n }\n }\n return "\\(bull)A\\(cow)B"\n }\n}\n``` | 6 | 0 | [] | 0 |
bulls-and-cows | O(n) time; O(1) space | on-time-o1-space-by-kingkingking888-b6qt | public class Solution {\n public String getHint(String secret, String guess) {\n int bulls=0;\n int cows=0;\n int[] count=new int[10];\n | kingkingking888 | NORMAL | 2015-10-31T21:38:41+00:00 | 2015-10-31T21:38:41+00:00 | 823 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int bulls=0;\n int cows=0;\n int[] count=new int[10];\n \n /*loop once \n 1231\n 0230\n \n 0231\n 1230\n \n gor guess, count--; for secret, count++\n */\n for(int i=0;i<secret.length();i++){\n int s=secret.charAt(i)-'0';\n int g=guess.charAt(i)-'0';\n if(s==g){\n bulls++;\n }else{\n if(count[g]>0){\n cows++;\n }\n if(count[s]<0){\n cows++;\n }\n count[g]--;\n count[s]++;\n }\n }\n return bulls+"A"+cows+"B";\n }\n} | 6 | 2 | [] | 0 |
bulls-and-cows | C++ simple solution using array with explaination (4ms) | c-simple-solution-using-array-with-expla-pqkq | If secret[i] and guess[i] match that's a bull - that's simple. Trickier part is about cows.\nWe use array numbers to remember if the any of digits (from 0 to 9) | paul7 | NORMAL | 2015-11-14T21:34:22+00:00 | 2015-11-14T21:34:22+00:00 | 1,198 | false | If **secret[i]** and **guess[i]** match that's a bull - that's simple. Trickier part is about cows.\nWe use array **numbers** to remember if the any of digits (from 0 to 9) is found in either *secret* or *guess*.\nWhen digit is found in *secret* we decrement value of **numbers[digit]** if digit is found in *guess* we increment it. \n\nThis is how we count cows:\n\n 1. if we need to decrement **numbers[digit]** and its current value is positive, that means we have seen it before in a different position, hence *cows++*;\n 2. if we need to increment **numbers[digit]** and its current value is negative, that means we've seen it as well. Again, *cows++*;\n\ncode:\n\n string getHint(string secret, string guess) {\n int length = secret.length(), bulls=0,cows=0;\n int numbers[10];\n memset(numbers, 0, sizeof(int)*10);\n \n for(int i=0;i<length;i++)\n {\n int a = secret[i]-'0';\n int b = guess[i]-'0';\n \n if(a==b){ bulls++; }\n else\n {\n cows+=(int)(numbers[a]>0) + (int)(numbers[b]<0); \n numbers[a]--;\n numbers[b]++;\n }\n }\n \n return to_string(bulls)+'A'+to_string(cows)+'B';\n } | 6 | 1 | ['Array', 'C++'] | 1 |
bulls-and-cows | My one-pass solution in C++ | my-one-pass-solution-in-c-by-nyycbd-0bdz | class Solution {\n public:\n string getHint(string secret, string guess) {\n vector<int>tb_guess(10),tb_secret(10);\n int A=0,B= | nyycbd | NORMAL | 2016-04-21T10:38:02+00:00 | 2016-04-21T10:38:02+00:00 | 764 | false | class Solution {\n public:\n string getHint(string secret, string guess) {\n vector<int>tb_guess(10),tb_secret(10);\n int A=0,B=0;\n for (int i=0;i<secret.size();++i){\n if (secret[i]==guess[i]) A++;\n else {\n tb_guess[guess[i]-'0']++;\n tb_secret[secret[i]-'0']++;\n }\n }\n for (int i=0;i<10;++i){\n B=B+ min(tb_guess[i],tb_secret[i]);\n }\n return to_string(A)+'A'+to_string(B)+'B';\n }\n }; | 6 | 0 | [] | 0 |
bulls-and-cows | Very straightforward solution | very-straightforward-solution-by-fisherc-pp7c | Also viewable here.\n\n\n public String getHint(String secret, String guess) {\n int[] secretCows = new int[10];\n int[] guessCows = new int[10 | fishercoder | NORMAL | 2016-10-28T16:58:52.898000+00:00 | 2016-10-28T16:58:52.898000+00:00 | 441 | false | Also viewable [here](https://github.com/fishercoder1534/Leetcode/blob/master/leetcode-algorithms/src/main/java/com/stevesun/solutions/BullsandCows.java).\n```\n\n public String getHint(String secret, String guess) {\n int[] secretCows = new int[10];\n int[] guessCows = new int[10];\n int bulls = 0;\n for(int i = 0; i < secret.length(); i++){\n if(guess.charAt(i) == secret.charAt(i)) bulls++;\n else{\n secretCows[Character.getNumericValue(secret.charAt(i))] ++;\n guessCows[Character.getNumericValue(guess.charAt(i))] ++;\n }\n }\n int cows = 0;\n for(int i = 0; i < 10; i++){\n cows += Math.min(secretCows[i], guessCows[i]);\n }\n return bulls + "A" + cows + "B";\n }\n``` | 6 | 0 | [] | 0 |
bulls-and-cows | Java solution beats 99%, no hashmap, only one loop | java-solution-beats-99-no-hashmap-only-o-980g | \npublic class Solution {\n public String getHint(String secret, String guess) {\n int s, g, size = secret.length();\n int bulls = 0, cows = 0; | ayiayiyo | NORMAL | 2016-08-17T18:38:33.336000+00:00 | 2016-08-17T18:38:33.336000+00:00 | 1,140 | false | ```\npublic class Solution {\n public String getHint(String secret, String guess) {\n int s, g, size = secret.length();\n int bulls = 0, cows = 0;\n int [] nums = new int [10];\n for (int i = 0; i < size; i++) {\n s = secret.charAt(i) - '0';\n g = guess.charAt(i) - '0';\n if (s == g)\n bulls ++;\n else{\n if (nums[s] < 0)\n cows++;\n nums[s]++;\n if (nums[g] > 0)\n cows++;\n nums[g]--;\n }\n }\n return bulls + "A" + cows + "B";\n }\n}\n``` | 6 | 0 | [] | 1 |
bulls-and-cows | Java 🔝| 0ms 🔥 | Beat 💯 | java-0ms-beat-by-sourabh-jadhav-h6km | \n# Code\n\nclass Solution {\n public String getHint(String secret, String guess) {\n int secdigs[] = new int[10];\n int guessdigs[] = new int[ | sourabh-jadhav | NORMAL | 2023-02-22T14:09:16.736973+00:00 | 2023-02-22T14:09:16.737005+00:00 | 651 | false | \n# Code\n```\nclass Solution {\n public String getHint(String secret, String guess) {\n int secdigs[] = new int[10];\n int guessdigs[] = new int[10];\n int bull = 0, cow = 0;\n\n for(int i = 0; i < secret.length() ; i ++) {\n if(secret.charAt(i) == guess.charAt(i)) {\n bull ++;\n }\n else {\n secdigs[secret.charAt(i) - \'0\'] ++;\n guessdigs[guess.charAt(i) - \'0\'] ++;\n }\n }\n\n for(int i = 0; i < 10; i ++) {\n int minVal = secdigs[i];\n if(minVal > guessdigs[i]) minVal = guessdigs[i];\n \n cow += minVal;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(bull).append("A").append(cow).append("B");\n\n return sb.toString();\n }\n}\n```\n\n | 5 | 0 | ['Java'] | 1 |
bulls-and-cows | Best JS Sol. - with less runtime ms & 99% memory beat 🙌 | best-js-sol-with-less-runtime-ms-99-memo-5k7h | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n1. The approach of th | Rajat310 | NORMAL | 2023-02-05T12:33:10.964223+00:00 | 2023-02-05T12:33:10.964279+00:00 | 280 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The approach of the function is to compare the characters of the two input strings sec and guess and count the number of matching characters in both the correct position (bulls) and the incorrect position (cows).\n\n2. The function uses an array raj of size 10 to keep track of the frequency of characters in the sec string. \n\n3. It increments the frequency of each character in the sec string and decrements the frequency of each character in the guess string.\n\n4. For each character in the input strings, the function checks if the characters match. \n\n5. If they match, it increments the bulls count. \n\n6. If they do not match, it checks if the frequency of the sec character in the raj array is less than 0 (meaning it has already been decremented from the guess string) or if the frequency of the guess character in the raj array is greater than 0 (meaning it has already been incremented from the sec string). \n\n7. If either of these conditions are true, it increments the cows count.\n\n8. Finally, the function returns a string in the format "bullsAcowB", where bulls is the number of correct characters in the correct position and cows is the number of correct characters in the incorrect position.\n\n\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n1. Here, n is the length of the input strings sec and guess. \n\n2. This is because the function is looping through the length of the input strings, performing constant time operations in each iteration.\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n1. Because as the size of the additional data structures used (i.e. the raj array and the variables bulls and cows) do not depend on the size of the input strings and are limited to a constant size.\n\n# Code\n```\n/**\n * @param {string} sec\n * @param {string} guess\n * @return {string}\n */\nvar getHint = function(sec, guess) {\n\n let bulls = 0;\n \n let cows = 0;\n \n let raj = Array(10).fill(0);\n \n // It creates an array with 10 elements and fills \n // each element with the value 0. The result will be \n // [0, 0, 0, 0, 0, 0, 0, 0, 0, 0].\n\n // The Array(10) constructor creates an array with \n // 10 empty slots (undefined values). The fill method \n // then replaces each undefined value with the value 0.\n \n for (let i=0; i<sec.length; i++) {\n\n let gu = parseInt(guess[i]);\n \n let secret = parseInt(sec[i]);\n \n if (secret === gu) {\n bulls++;\n continue;\n }\n\n if (raj[secret] < 0) { \n cows++;\n }\n \n if (raj[gu] > 0) { \n cows++;\n }\n \n raj[secret]++;\n raj[gu]--; \n }\n \n return (`${bulls}A${cows}B`);\n \n};\n```\n\n\n | 5 | 0 | ['JavaScript'] | 0 |
bulls-and-cows | Easy Python Solution Using Counter | easy-python-solution-using-counter-by-la-77mt | Code\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n dic=Counter(secret)-Counter(guess)\n cnt=0\n for i in ran | Lalithkiran | NORMAL | 2023-02-01T18:22:19.487459+00:00 | 2023-02-01T18:22:19.487512+00:00 | 1,531 | false | # Code\n```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n dic=Counter(secret)-Counter(guess)\n cnt=0\n for i in range(len(secret)):\n if secret[i]==guess[i]:\n cnt+=1\n cnt2=len(secret)-sum(dic.values())-cnt\n return str(cnt)+"A"+str(cnt2)+"B"\n``` | 5 | 0 | ['Counting', 'Python3'] | 0 |
bulls-and-cows | python3, simple solution, defaultdict() for cows | python3-simple-solution-defaultdict-for-y3iop | ERROR: type should be string, got "https://leetcode.com/submissions/detail/875564006/\\nRuntime: 30 ms, faster than 99.56% of Python3 online submissions for Bulls and Cows. \\nMemory Usage: 14 MB," | nov05 | NORMAL | 2023-01-09T05:50:01.345723+00:00 | 2023-01-10T16:44:58.837885+00:00 | 896 | false | ERROR: type should be string, got "https://leetcode.com/submissions/detail/875564006/\\nRuntime: **30 ms**, faster than 99.56% of Python3 online submissions for Bulls and Cows. \\nMemory Usage: 14 MB, less than 29.43% of Python3 online submissions for Bulls and Cows. \\n```\\nclass Solution:\\n def getHint(self, secret: str, guess: str) -> str:\\n bulls, cows, ds, dg = 0, 0, defaultdict(lambda:0), defaultdict(lambda:0)\\n for s,g in zip(secret, guess):\\n if s==g:\\n bulls += 1\\n continue\\n ds[s]+=1; dg[g]+=1\\n for s in ds:\\n if s in dg:\\n cows += min(ds[s], dg[s])\\n return f\\'{bulls}A{cows}B\\'\\n```" | 5 | 1 | ['Python', 'Python3'] | 1 |
bulls-and-cows | ✔Easy Python solution using Hashmap | easy-python-solution-using-hashmap-by-sa-bpxq | Intuition\nFor bulls we have to check for the digits having same position in both the strings i.e. secret and guess, then will count for the rest of the digits | Saumya_Kumar | NORMAL | 2023-01-04T16:13:17.710246+00:00 | 2023-01-04T16:13:17.710299+00:00 | 676 | false | # Intuition\nFor bulls we have to check for the digits having same position in both the strings i.e. secret and guess, then will count for the rest of the digits which are common in both strings.\n\n# Approach\nWe will take **two dictionary** for **counting the frequency** of each digit occured in the respective string.\nThen will check for **similar digits** having **same position** in strings and **decrease their frequency** value from each dictionary.\nNow for cow we will check for **common digits** which have non zero value in both dictionaries and will add the **minimum** of the frequency into cows value.\n\n# Complexity\n- Time complexity:\n**O(n)**\n\n- Space complexity:\n**O(n)**\n\n# Code\n```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n a={}\n b={}\n for i in secret: #Frequency of digits in secret\n if i in a:\n a[i]+=1\n else:\n a[i]=1\n for i in guess: #Frequency of digits in guess\n if i in b:\n b[i]+=1\n else:\n b[i]=1\n bulls=0\n for i in range(len(secret)): #Counting bulls\n if secret[i]==guess[i]:\n bulls+=1\n a[secret[i]]-=1\n b[secret[i]]-=1\n cows=0\n for i in a: #Counting cows\n if i in b:\n cows+=min(a[i],b[i])\n res=str(bulls)+"A"+str(cows)+"B"\n return res\n``` | 5 | 0 | ['Python3'] | 0 |
bulls-and-cows | A simple and clear python-solution | a-simple-and-clear-python-solution-by-m-fqfia | \n\tclass Solution:\n\t\tdef getHint(self, secret: str, guess: str) -> str:\n\t\t\tA = 0\n\t\t\tB = 0\n\t\t\tfor index in range(len(secret) - 1, -1, -1):\n\t\t\ | m-d-f | NORMAL | 2020-09-13T23:41:18.852243+00:00 | 2020-09-14T06:09:38.738764+00:00 | 679 | false | \n\tclass Solution:\n\t\tdef getHint(self, secret: str, guess: str) -> str:\n\t\t\tA = 0\n\t\t\tB = 0\n\t\t\tfor index in range(len(secret) - 1, -1, -1):\n\t\t\t\tif secret[index] == guess[index]:\n\t\t\t\t\tA += 1\n\t\t\t\t\tsecret = secret[: index] + secret[index + 1 :]\n\t\t\t\t\tguess = guess[: index] + guess[index + 1 :]\n \n\t\t\tfor first in secret:\n\t\t\t\tif first in guess:\n\t\t\t\t\tB += 1\n\t\t\t\t\tguess = guess.replace(first, "", 1)\n\n\t\t\treturn f"{A}A{B}B"\n\t\t\'\'\'\nThe first loop finds identities found in the same index\nThe second loop finds identities that are not in the same index | 5 | 0 | ['Python3'] | 2 |
bulls-and-cows | Short and easy solution in C++, O(N), O(1) space | short-and-easy-solution-in-c-on-o1-space-yb0m | We can calculate count of Bulls easily by just couting where characters matches in the 2 given strings. Also, in the same iteration when characters don\'t match | vikasbhandari162 | NORMAL | 2020-09-11T06:38:16.657717+00:00 | 2020-09-11T06:39:22.229592+00:00 | 636 | false | We can calculate count of ```Bulls``` easily by just couting where characters matches in the 2 given strings. Also, in the same iteration when characters don\'t match we can keep their count in mp1(for ```secret``` ) and mp2(for ```guess```) . Then we can iterate one of these constant size array and find the minimum of count of all the characters in both of these arrays and in that way we can be sure that that this character occurs atleast this much time in both strings and hence this number contributes to the ```Cow``` variable.\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int mp1[10] = {0};\n int mp2[10] = {0};\n int bull=0,cow=0;\n for(int i=0;i<secret.length();i++) {\n if(secret[i]==guess[i]) {\n bull++;\n } else {\n mp1[secret[i]-\'0\']++;\n mp2[guess[i]-\'0\']++;\n }\n }\n \n for(int i=0;i<10;i++) {\n if(mp1[i]!=0 && mp2[i]!=0) {\n cow += min(mp1[i], mp2[i]);\n \n }\n }\n \n return to_string(bull) + "A" + to_string(cow) + "B";\n \n }\n};\n```\n\nRuntime : 8ms\nMemory Usage: 6.5 MB | 5 | 0 | ['Array', 'String', 'C'] | 1 |
bulls-and-cows | Python Simple Solution Explained (video + code) | python-simple-solution-explained-video-c-h9kz | \nhttps://www.youtube.com/watch?v=pHm7VOMzJpI\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bulls = 0\n bucket = [0 | spec_he123 | NORMAL | 2020-09-10T15:18:20.417853+00:00 | 2020-09-10T15:18:20.417893+00:00 | 712 | false | [](https://www.youtube.com/watch?v=pHm7VOMzJpI)\nhttps://www.youtube.com/watch?v=pHm7VOMzJpI\n```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bulls = 0\n bucket = [0] * 10\n \n for s, g in zip(secret, guess):\n if s == g:\n bulls += 1\n else:\n bucket[int(s)] += 1\n bucket[int(g)] -= 1\n return f\'{bulls}A{len(secret) - bulls - sum(x for x in bucket if x > 0)}B\'\n``` | 5 | 0 | ['Python', 'Python3'] | 0 |
bulls-and-cows | Clean and clear Java O(n) Solution | clean-and-clear-java-on-solution-by-xula-zc2o | public class Solution {\n public String getHint(String secret, String guess) {\n int A = 0, B = 0;\n int[] cnt = new int[10];\n | xulai_cao | NORMAL | 2015-10-31T02:32:00+00:00 | 2015-10-31T02:32:00+00:00 | 1,018 | false | public class Solution {\n public String getHint(String secret, String guess) {\n int A = 0, B = 0;\n int[] cnt = new int[10];\n for(int i=0; i<secret.length(); ++i){\n if(secret.charAt(i) == guess.charAt(i)) ++A;\n else{\n if(++cnt[secret.charAt(i)-'0'] <= 0) ++B;\n if(--cnt[guess.charAt(i)-'0']>=0) ++B;\n }\n }\n return A + "A" + B + "B";\n }\n } | 5 | 0 | ['Array', 'Java'] | 0 |
bulls-and-cows | Two AC C++ solution, 92 ms and 4 ms. | two-ac-c-solution-92-ms-and-4-ms-by-heii-aomz | The basic idea of this problem is calculate Bulls number firstly, then calculate Cows number.\nThis is my first solution code:\n\n string getHint(string s, s | heii0w0rid | NORMAL | 2015-11-02T06:55:51+00:00 | 2015-11-02T06:55:51+00:00 | 1,038 | false | The basic idea of this problem is calculate Bulls number firstly, then calculate Cows number.\nThis is my first solution code:\n\n string getHint(string s, string g) \n {\n \tif (s.empty())\n \t\treturn "0A0B";\n \tint i, j, a, b;\n \tint sz = s.size();\n \ta = b = 0;\n \tvector<int> vs(sz, 1);\n \tvector<int> vg(sz, 1);\n \tfor (i = 0; i < sz; ++i)\n \t{\n \t\tif (s[i] == g[i])\n \t\t{\n \t\t\t++a;\n \t\t\tvs[i] = vg[i] = 0;\n \t\t\tcontinue;\n \t\t}\n \t}\n \tfor (i = 0; i < sz; ++i)\n \t{\n \t\tif (0 == vs[i])\n \t\t\tcontinue;\n \t\tfor (j = 0; j < sz; ++j)\n \t\t{\n \t\t\tif (0 == vg[j] || i == j)\n \t\t\t\tcontinue;\n \t\t\tif (s[i] == g[j])\n \t\t\t{\n \t\t\t\t++b;\n \t\t\t\tvg[j] = 0;\n \t\t\t\tbreak;\n \t\t\t}\n \t\t}\n \t}\n \treturn to_string(a) + "A" + to_string(b) + "B";\n }\n\nIt costs 92 ms.\n\nThe problem also told us character only '0'~'9' be used. Then the code can be improved as follow:\n\n string getHint(string s, string g)\n {\n \tif (s.empty())\n \t\treturn "0A0B";\n \tint i, j, a, b;\n \tint sz = s.size();\n \ta = b = 0;\n \tvector<int> vs(10, 0);\n \tvector<int> vg(10, 0);\n \tfor (i = 0; i < sz; ++i)\n \t{\n \t\tif (s[i] == g[i])\n \t\t{\n \t\t\t++a;\n \t\t\tcontinue;\n \t\t}\n \t\t++vs[s[i] - '0'];\n \t\t++vg[g[i] - '0'];\n \t}\n \tfor (i = 0; i < 10; ++i)\n \t\tb += min(vs[i], vg[i]);\n \treturn to_string(a) + "A" + to_string(b) + "B";\n }\n\nIn the first loop calculate the digits' ('0'~'9') number that didn't paired. In the second loop choose the smaller number means at least these numbers of digits could be paired but at wrong position now. | 5 | 0 | ['C++'] | 0 |
bulls-and-cows | Java solution without HashTable | java-solution-without-hashtable-by-lyxst-anzj | public String getHint(String secret, String guess) {\n\n int bull=0;\n int cow=0;\n int[] marks=new int[10];\n int[] markg=new int[1 | lyxstarter | NORMAL | 2016-05-09T04:05:07+00:00 | 2016-05-09T04:05:07+00:00 | 1,072 | false | public String getHint(String secret, String guess) {\n\n int bull=0;\n int cow=0;\n int[] marks=new int[10];\n int[] markg=new int[10];\n for(int i =0;i<secret.length();i++){\n if(secret.charAt(i)==guess.charAt(i))\n bull++;\n marks[secret.charAt(i)-'0']++;\n markg[guess.charAt(i)-'0']++;\n }\n for(int i =0;i<10;i++){\n cow+=Math.min(marks[i],markg[i]);\n }\n StringBuffer sb=new StringBuffer();\n sb.append(bull);\n sb.append("A");\n sb.append(cow-bull);\n sb.append("B");\n String returnStr=new String(sb);\n return returnStr;\n\n } | 5 | 0 | ['Java'] | 0 |
bulls-and-cows | simple c++ | simple-c-by-astha-vq5z | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | astha_ | NORMAL | 2025-01-03T10:34:49.364402+00:00 | 2025-01-03T10:34:49.364402+00:00 | 612 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
string getHint(string secret, string guess) {
int bulls=0;
unordered_map<char,int>mp;
string ng="";
for(int i=0;i<secret.size();i++){
if(secret[i]==guess[i]){
bulls++;
}
else{
ng+=guess[i];
mp[secret[i]]++;
}
}
int cows=0;
for(int i=0;i<ng.size();i++){
if(mp.find(ng[i])!=mp.end()){
cows++;
mp[ng[i]]--;
if(mp[ng[i]]==0){
mp.erase(ng[i]);
}
}
}
string ans="";
ans+=to_string(bulls);
ans+='A';
ans+=to_string(cows);
ans+='B';
return ans;
}
};
``` | 4 | 0 | ['C++'] | 1 |
bulls-and-cows | 🚀🚀Java Solution Using HashMap with O(n)TC🚀🚀 | java-solution-using-hashmap-with-ontc-by-yr5m | Intuition\nThe problem is about comparing two strings, secret and guess, to determine how many characters are "bulls" (correct in both position and character) a | Raghu_ram9000 | NORMAL | 2024-08-19T16:31:31.812750+00:00 | 2024-08-19T16:31:31.812776+00:00 | 187 | false | # Intuition\nThe problem is about comparing two strings, secret and guess, to determine how many characters are "bulls" (correct in both position and character) and how many are "cows" (correct in character but not in position). The challenge is to do this efficiently, ensuring that we don\u2019t double-count any characters.\n\n# Approach\n1.Map to Track Frequency:\n\nFirst, we build a frequency map of characters in the secret string. This map will help us determine how many times a character appears in the secret string, which is useful for counting both bulls and cows.\n\n\n2.First Pass - Counting Bulls:\n\n We iterate through both secret and guess simultaneously.\n For each index i, if the characters in both strings match (i.e., secret[i] == guess[i]), it\'s a bull. We increment the bulls_count and decrement the frequency of this character in the map.\nIf the frequency of the character in the map reaches zero, we remove it from the map to prevent double-counting later.\n\n\n3.Second Pass - Counting Cows:\nWe iterate through the strings again.\nFor each index i, if the characters don\'t match (i.e., secret[i] != guess[i]), we check if the guess[i] character exists in the map and has a positive frequency.\nIf it does, it\'s a cow. We increment the cows_count, decrement the frequency of this character in the map, and remove it if the frequency becomes zero.\nThis ensures that we only count characters that weren\'t already counted as bulls and that we don\'t double-count any characters.\n\n4.Building the Result:\n\nFinally, we construct the result string in the format "xAyB", where x is the number of bulls and y is the number of cows, using a StringBuilder for efficiency.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```java []\nclass Solution {\n public String getHint(String secret, String guess) {\n int bulls_count=0;\n int cows_count=0;\n\n Map<Character,Integer>map=new HashMap<>();\n for(char ch:secret.toCharArray())\n {\n map.put(ch,map.getOrDefault(ch,0)+1);\n }\n\n for(int i=0;i<secret.length();i++)\n {\n char char1= secret.charAt(i);\n char char2=guess.charAt(i);\n\n if(char1==char2)\n {\n bulls_count++;\n map.put(char2,map.get(char2)-1);\n if (map.get(char2) == 0) \n {\n map.remove(char2);\n }\n }\n }\n\n for(int i=0;i<secret.length();i++)\n {\n char char1= secret.charAt(i);\n char char2=guess.charAt(i);\n\n if(char1 != char2 && map.containsKey(char2) && map.get(char2) > 0)\n {\n {\n cows_count++;\n map.put(char2,map.get(char2)-1);\n if (map.get(char2) == 0) \n {\n map.remove(char2);\n }\n }\n }\n }\n\n\n StringBuilder sb1 = new StringBuilder(Integer.toString(acount));\n StringBuilder sb2 = new StringBuilder(Integer.toString(bcount));\n StringBuilder ans = new StringBuilder();\n ans.append(acount).append("A").append(bcount).append("B");\n\n String str=ans.toString();\n\n return str;\n\n\n\n\n \n\n \n }\n}\n``` | 4 | 0 | ['Hash Table', 'Math', 'String', 'Brainteaser', 'Counting', 'Java'] | 0 |
bulls-and-cows | 💥C++ | Beats 100% 🤘🏻 | hashTable 💥| Begineer friendly | c-beats-100-hashtable-begineer-friendly-jwx24 | UPVOTE IF SOLUTION SEEMS GOOD TO YOU.\n\n# Code\n\n\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int count = 0;\n | Kanishq_24je3 | NORMAL | 2024-02-23T07:32:23.338935+00:00 | 2024-02-23T07:32:23.338966+00:00 | 354 | false | # UPVOTE IF SOLUTION SEEMS GOOD TO YOU.\n\n# Code\n```\n\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int count = 0;\n int mount = 0; \n string ans = "";\n int hash[256] = {};\n for(int i = 0; i<secret.length();i++) {\n if(secret[i] == guess[i]) {\n count++;\n }\n }\n \n for(int i = 0; i < secret.length();i++) {\n hash[secret[i]]++;\n }\n for(int i = 0; i < guess.length();i++) {\n if(hash[guess[i]] > 0) { \n mount++; \n hash[guess[i]]--; \n }\n }\n mount -= count;\n ans += to_string(count) + \'A\' + to_string(mount) + \'B\'; \n return ans;\n }\n}; \n\n``` | 4 | 0 | ['C++'] | 0 |
bulls-and-cows | Python Easy Solution (Beats 99.5%) | python-easy-solution-beats-995-by-harsh4-u8la | 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 | Harsh425 | NORMAL | 2023-01-10T12:57:49.155037+00:00 | 2023-01-10T12:57:49.155091+00:00 | 1,109 | 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 def getHint(self, secret: str, guess: str) -> str:\n lst1 = list(secret)\n lst2 = list(guess)\n x = 0\n for i in range(len(lst2)):\n if lst1[i] == lst2[i]:\n x += 1\n y = len(lst1) - sum((Counter(lst1) - Counter(lst2)).values()) - x\n res = \'\'.join(str(x)+\'A\'+str(y)+\'B\')\n return res\n``` | 4 | 0 | ['Python3'] | 0 |
bulls-and-cows | C++ Good Code Quality One pass solution with great explanation. | c-good-code-quality-one-pass-solution-wi-qpja | Explanation:\nThe statement says that bull is a character which matches exactly to the guess position in secret.\nand Cows are character which are not in correc | akgupta0777 | NORMAL | 2023-01-06T10:03:13.905215+00:00 | 2023-01-13T09:29:35.870238+00:00 | 433 | false | **Explanation:**\nThe statement says that bull is a character which matches exactly to the guess position in secret.\nand Cows are character which are not in correct position but can be rearranged to form the secret.\nIf we know the appearance of a character in secret appears before or not we can solve this problem easily\n\nExample \nsecret = "1807"\nguess = "7810"\nOutput = "1A3B" (1 bull and 3 Cows)\n\nWe can use a freq array to know appearance of a character.\n\n**How ?**\nWe will increment count in secret string character in hope of finding the same character that decrements this count\nin the guess string.\nSimilarly we will decrement count in guess string character in hope of finding the same character that increments this count\nin the secret string.\nIn the above Example\n\'1\' is the character in secret string that will be decremented by \'1\' in guessing string.\n\n**Algorithm**\nCreate a vector to store frequencies of characters.\nRun a loop until secret length to process all characters.\nIf we found two same characters at same positions increment bulls.\nElse check if the secret character is found by guessing character or vice versa, If yes then increment cows.\nFinally construct the string in the order of given output.\nReturn output string. \n\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n vector<int> freq(10,0);\n string hint;\n int bulls=0,cows=0;\n\n for(int i=0;i<secret.size();++i){\n if(guess[i]==secret[i]){\n bulls++;\n }else {\n if(freq[secret[i]-\'0\']++ < 0) cows++;\n if(freq[guess[i]-\'0\']-- > 0) cows++;\n }\n }\n hint=to_string(bulls)+"A"+to_string(cows)+"B";\n return hint;\n }\n};\n``` | 4 | 0 | ['Array', 'Hash Table', 'Greedy', 'Counting', 'C++'] | 0 |
bulls-and-cows | Easy Java o(N) Solution by counting | easy-java-on-solution-by-counting-by-aay-ou2i | Intuition : Counting bulls and cows\n Describe your first thoughts on how to solve this problem. \n\n\n# Approach : Counting bulls by comparing and cows with th | aayush_sagar | NORMAL | 2023-01-03T07:24:07.365526+00:00 | 2023-01-14T18:18:55.758238+00:00 | 865 | false | # Intuition : Counting bulls and cows\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Approach : Counting bulls by comparing and cows with the help of an array\n<!-- Describe your approach to solving the problem. -->\n\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 {\n public String getHint(String secret, String guess) {\n //check same character on both string on same index for bull\n int bull =0;\n for(int i=0; i< secret.length(); i++){\n if(secret.charAt(i) == guess.charAt(i) ) bull++;\n }\n\n // for cows count occurance of every number and save it in Array\n int count =0;\n int[] arr = new int[10];\n for(int i=0; i<guess.length(); i++){\n int n = guess.charAt(i) -\'0\';\n arr[n]++;\n }\n \n for(int i=0; i<guess.length(); i++){\n int n = secret.charAt(i) -\'0\';\n if(arr[n] != 0){\n arr[n]--;\n count++;\n }\n }\n count = count -bull; \n String s= bull+"A"+count+"B";\n\n return s;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
bulls-and-cows | Very Easy Implementation in DP with 70% runtime. | very-easy-implementation-in-dp-with-70-r-2zee | \nclass Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :rtype: str\n | amit321kumar | NORMAL | 2022-08-30T13:21:24.093198+00:00 | 2022-08-30T13:21:24.093235+00:00 | 428 | false | ```\nclass Solution(object):\n def getHint(self, secret, guess):\n """\n :type secret: str\n :type guess: str\n :rtype: str\n """\n bulls=0\n cows=0\n d1=collections.Counter(secret)\n d2=collections.Counter(guess)\n for i in d1:\n if i in d2:\n cows+=min(d1[i],d2[i])\n for i in range(len(secret)):\n if secret[i] == guess[i]:\n bulls+=1\n return str(bulls) + "A" + str(cows-bulls) + \'B\'\n\n\n``` | 4 | 0 | ['Dynamic Programming', 'Python'] | 0 |
bulls-and-cows | Layman Approach to understanding the problem statement | layman-approach-to-understanding-the-pro-4u9f | Ok, So let me explain you this in very layman terms.\n\n-So you know how to count for bulls, which ever character(digit) is at same place, you increase counter. | bitbybits | NORMAL | 2022-01-26T12:29:58.583612+00:00 | 2022-01-26T12:29:58.583645+00:00 | 102 | false | Ok, So let me explain you this in very layman terms.\n\n-So you know how to count for bulls, which ever character(digit) is at same place, you increase counter. Straight forward.\n-Coming to count cows. So think it in this way.\n\nIf you have bulls that mean "n" digits are at same place. So assume you removed the matching char from both the arrays. For Example :\n \n\tsecret "1122"\n guess "2212"\nWe found 2 at 3rd place, which is same. So we remove it from both arrays and we will be having - :\n \n\tsecret "112"\n\tguess "221"\nNow to get the answer for num of cows, just calculate how many digits you can shuffle in **guess array** to make it similar as **secret array**. So in above example you can shuffle the guess array in 2 possible ways ( P1 & P2 ) :\n\n\n\t P1 P2 \n\tsecret "112" "112"\n guess "122" "212"\nIn both ways you can only have 2 digits at same place. And So your count for cows would be "2". | 4 | 0 | [] | 0 |
bulls-and-cows | 2-pass & 1-pass solution Python | 2-pass-1-pass-solution-python-by-kryuki-f0lh | 2-pass solution\n\nfrom collections import Counter\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n secret_non_bull, guess_no | kryuki | NORMAL | 2021-12-05T07:44:40.015565+00:00 | 2021-12-05T07:44:59.154576+00:00 | 483 | false | **2-pass solution**\n```\nfrom collections import Counter\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n secret_non_bull, guess_non_bull = [], []\n num_bulls = 0\n for char1, char2 in zip(secret, guess):\n if char1 == char2:\n num_bulls += 1\n else:\n secret_non_bull.append(char1)\n guess_non_bull.append(char2)\n \n secret_counter, guess_counter = Counter(secret_non_bull), Counter(guess_non_bull)\n \n num_cows = 0\n for word, cnt in guess_counter.items():\n num_cows += min(secret_counter[word], cnt)\n \n \n return str(num_bulls) + \'A\' + str(num_cows) + \'B\'\n```\n\n**1-pass solution**\n```\nfrom collections import defaultdict\n\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n diff_dict = defaultdict(int)\n num_bulls, num_cows = 0, 0\n \n for char1, char2 in zip(secret, guess):\n if char1 == char2:\n num_bulls += 1\n else:\n if diff_dict[char2] < 0:\n num_cows += 1\n diff_dict[char2] += 1\n \n if diff_dict[char1] > 0:\n num_cows += 1\n diff_dict[char1] -= 1\n \n return str(num_bulls) + \'A\' + str(num_cows) + \'B\'\n``` | 4 | 0 | ['Python', 'Python3'] | 0 |
bulls-and-cows | JavaScript / TypeScript Solution | javascript-typescript-solution-by-eddyhd-y8m9 | // JS\n// Runtime: 84 ms, faster than 88.14% of JavaScript online submissions for Bulls and Cows.\n// Memory Usage: 39.3 MB, less than 46.05% of JavaScript onli | eddyhdzg | NORMAL | 2020-09-11T21:12:23.847357+00:00 | 2020-09-11T21:12:23.847416+00:00 | 485 | false | // JS\n// Runtime: 84 ms, faster than 88.14% of JavaScript online submissions for Bulls and Cows.\n// Memory Usage: 39.3 MB, less than 46.05% of JavaScript online submissions for Bulls and Cows.\n```\nvar getHint = function (secret, guess) {\n let bulls = 0;\n let cows = 0;\n const hash = {};\n\n for (let i = 0; i < secret.length; i++) {\n if (secret[i] === guess[i]) {\n bulls++;\n } else if (secret[i] in hash) hash[secret[i]]++;\n else hash[secret[i]] = 1;\n }\n\n for (let i = 0; i < guess.length; i++) {\n if (secret[i] !== guess[i] && hash[guess[i]]) {\n cows++;\n hash[guess[i]]--;\n }\n }\n\n return `${bulls}A${cows}B`;\n};\n```\n\n// TS\n// Runtime: 76 ms, faster than 100.00% of TypeScript online submissions for Bulls and Cows.\n// Memory Usage: 40.3 MB, less than 40.00% of TypeScript online submissions for Bulls and Cows.\n```\nfunction getHint(secret: string, guess: string): string {\n let bulls = 0;\n let cows = 0;\n const hash: { [key: string]: number } = {};\n\n for (let i = 0; i < secret.length; i++) {\n if (secret[i] === guess[i]) {\n bulls++;\n } else if (secret[i] in hash) hash[secret[i]]++;\n else hash[secret[i]] = 1;\n }\n\n for (let i = 0; i < guess.length; i++) {\n if (secret[i] !== guess[i] && hash[guess[i]]) {\n cows++;\n hash[guess[i]]--;\n }\n }\n\n return `${bulls}A${cows}B`;\n}\n```\nMore leetcode TypeScript solutions at https://github.com/eddyhdzg/leetcode-typescript-solutions\n | 4 | 0 | ['TypeScript', 'JavaScript'] | 0 |
bulls-and-cows | Java with some comments | HashMap | Two Pass | java-with-some-comments-hashmap-two-pass-vam4 | \nclass Solution {\n public String getHint(String secret, String guess) {\n // first pass determine the A\n Map<Character, Integer> map1 = new | Hao_Code | NORMAL | 2020-09-10T14:38:33.758844+00:00 | 2020-09-10T14:38:33.758871+00:00 | 375 | false | ```\nclass Solution {\n public String getHint(String secret, String guess) {\n // first pass determine the A\n Map<Character, Integer> map1 = new HashMap<>();\n Map<Character, Integer> map2 = new HashMap<>();\n int A = 0;\n for(int i = 0; i < secret.length(); i++) {\n map1.put(secret.charAt(i), map1.getOrDefault(secret.charAt(i), 0) + 1);\n map2.put(guess.charAt(i), map2.getOrDefault(guess.charAt(i), 0) + 1);\n if(secret.charAt(i) == guess.charAt(i)) {\n A++;\n }\n }\n // Second Pass find B\n int B = 0;\n for(char c: map1.keySet()) {\n if(map2.containsKey(c)) {\n // we always take the smallest value form map1 or map2\n B = B + Math.min(map1.get(c), map2.get(c));\n }\n }\n // if some number is definded as \'A\', then it must be contain in \'B\'. Therefeore, we should minus A.\n B = B - A;\n return A + "A" + B + "B";\n \n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
bulls-and-cows | JavaScript one pass with explanation and comments | javascript-one-pass-with-explanation-and-y9dc | \n/*\nbulls : exact\ncows: number match but position does not\n\ncreate a hashmap O(1) since it\'s fixed at most letters in alphabet {num:freq}\niterate through | alexanderywang | NORMAL | 2020-09-10T12:43:54.666568+00:00 | 2020-09-10T12:43:54.666628+00:00 | 117 | false | ```\n/*\nbulls : exact\ncows: number match but position does not\n\ncreate a hashmap O(1) since it\'s fixed at most letters in alphabet {num:freq}\niterate through both strings at once, for every bull, keep a counter\n\nif match, don\'t update map. \'lock\' in the position\nelse \nif map[secret letter] is negative (from a previous guess) -> cow++\nif map[guess letter] is positive (from a previous secret) -> cow++\nfor guess letter, map.set -1\nfor secret, map.set + 1\n*/\n/**\n * @param {string} secret\n * @param {string} guess\n * @return {string}\n */\nvar getHint = function(secret, guess) {\n let map = new Map(); // {num:count}\n let cows = 0;\n let bulls = 0;\n for (let i = 0; i < secret.length; i++){\n let g = guess[i];\n let s = secret[i];\n if (s === g){\n bulls++;\n } else {\n if (map.has(s) && map.get(s) < 0) cows++;\n if (map.has(g) && map.get(g) > 0) cows++;\n map.set(s, (map.get(s) || 0) + 1)\n map.set(g, (map.get(g) || 0) - 1)\n }\n }\n return `${bulls}A${cows}B`;\n};\n``` | 4 | 0 | [] | 0 |
bulls-and-cows | Python simple intuitive solution | python-simple-intuitive-solution-by-yehu-ho9o | \nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bull, cow = 0, 0\n # keep in dict indexes of each numer:\n my_d | yehudisk | NORMAL | 2020-09-10T07:52:45.756649+00:00 | 2020-09-10T07:52:45.756703+00:00 | 275 | false | ```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bull, cow = 0, 0\n # keep in dict indexes of each numer:\n my_dict = defaultdict(list)\n for i, num in enumerate(secret):\n my_dict[num].append(i)\n temp = ""\n # find exact matches:\n for i, num in enumerate(guess):\n if my_dict.get(num):\n if i in my_dict.get(num):\n bull+=1\n my_dict[num].remove(i)\n temp+=\'a\'\n else:\n temp+=num\n # find numbers in wrong positions:\n for i, num in enumerate(temp):\n if my_dict.get(num):\n cow+=1\n my_dict[num].pop(-1)\n \n return str(bull)+\'A\'+str(cow)+\'B\'\n``` | 4 | 0 | ['Python3'] | 0 |
bulls-and-cows | why is this an easy question? | why-is-this-an-easy-question-by-d00mer-po0h | I think this should be marked as medium, the only easy part of this question is easily messing up edge cases like:\n\n"1122"\n"1222"\n | d00mer | NORMAL | 2020-08-19T20:48:43.859827+00:00 | 2020-08-19T20:49:17.649960+00:00 | 207 | false | I think this should be marked as medium, the only easy part of this question is easily messing up edge cases like:\n```\n"1122"\n"1222"\n``` | 4 | 0 | [] | 1 |
bulls-and-cows | Decent Python Code Beats 99.77% | decent-python-code-beats-9977-by-xianggg-h8jf | \n def getHint(self, secret: str, guess: str) -> str:\n c, b = 0, 0\n for i in range(len(secret)):\n if secret[i] == guess[i]: b += | xianggg | NORMAL | 2020-06-18T14:37:05.582074+00:00 | 2020-06-24T14:09:24.056834+00:00 | 342 | false | ```\n def getHint(self, secret: str, guess: str) -> str:\n c, b = 0, 0\n for i in range(len(secret)):\n if secret[i] == guess[i]: b += 1\n for i in range(len(secret)):\n if secret[i] in guess:\n c += min(secret.count(secret[i]), guess.count(secret[i]))\n guess = guess.replace(secret[i], "")\n return str(b) + "A" + str(c-b) + "B"\n``` | 4 | 1 | ['Python3'] | 3 |
bulls-and-cows | c++ O(n) faster than 99% | c-on-faster-than-99-by-siddharthchabuksw-pdxa | \nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int bull = 0, cow = 0, i, n = secret.length();\n int countS[10] = | siddharthchabukswar | NORMAL | 2019-08-31T07:13:56.678166+00:00 | 2019-08-31T07:13:56.678201+00:00 | 423 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int bull = 0, cow = 0, i, n = secret.length();\n int countS[10] = {0};\n int countG[10] = {0};\n for(i=0; i<n; i++){\n if(secret[i] == guess[i]) bull++;\n else{\n countS[secret[i] - \'0\']++;\n countG[guess[i] - \'0\']++;\n }\n }\n \n for(i=0;i<10;i++){\n cow += min(countS[i], countG[i]);\n } \n return (to_string(bull)+"A"+to_string(cow)+"B");\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
bulls-and-cows | C# count A first then B | c-count-a-first-then-b-by-bacon-xetb | \npublic class Solution {\n public string GetHint(string secret, string guess) {\n var n = secret.Length;\n\n var countA = 0;\n var coun | bacon | NORMAL | 2019-06-02T21:01:32.033831+00:00 | 2019-06-02T21:01:32.033877+00:00 | 176 | false | ```\npublic class Solution {\n public string GetHint(string secret, string guess) {\n var n = secret.Length;\n\n var countA = 0;\n var countB = 0;\n\n var charAndCountSecret = new int[256];\n var charAndCountGuess = new int[256];\n for (int i = 0; i < n; i++) {\n if (secret[i] == guess[i]) {\n countA++;\n } else {\n charAndCountSecret[secret[i]]++;\n charAndCountGuess[guess[i]]++;\n }\n }\n\n for (int i = 0; i < 256; i++) {\n countB += Math.Min(charAndCountSecret[i], charAndCountGuess[i]);\n }\n\n return $"{countA}A{countB}B";\n }\n}\n\n``` | 4 | 0 | [] | 0 |
bulls-and-cows | javascript beats 100%. Self explanatory | javascript-beats-100-self-explanatory-by-6b45 | ``` var getHint = function(secret, guess) { let guessArr = new Array(10).fill(0); let secretArr = new Array(10).fill(0); let bull = 0; let cow = 0; getBul | blbb1111 | NORMAL | 2018-10-30T21:31:56.665231+00:00 | 2018-10-30T21:31:56.665288+00:00 | 416 | false | ```
var getHint = function(secret, guess) {
let guessArr = new Array(10).fill(0);
let secretArr = new Array(10).fill(0);
let bull = 0; let cow = 0;
getBulls();
getCows();
cow = cow - bull;
return `${bull}A${cow}B`;
function getBulls() {
for (let i = 0; i < secret.length; i++) {
secretArr[Number(secret[i])]++; guessArr[Number(guess[i])]++;
if (secret[i] === guess[i]) {
bull++;
}
}
};
function getCows() {
for (let i = 0; i < 10; i++) {
cow += Math.min(Number(guessArr[i]), Number(secretArr[i]));
}
};
};
``` | 4 | 0 | [] | 2 |
bulls-and-cows | Frequency Maps |✅ EZPZ🍋🤏| With Explanation | frequency-maps-ezpz-with-explanation-by-whnge | Intuition\n Describe your first thoughts on how to solve this problem. \nThere are two things to consider:\n1. Correct digits placed in correct locations\n2. Co | jorelm68 | NORMAL | 2024-11-14T18:24:42.015159+00:00 | 2024-11-14T18:24:42.015193+00:00 | 346 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are two things to consider:\n1. Correct digits placed in correct locations\n2. Correct digits placed in incorrect locations\nWe will first count the amount of correct digits placed in correct locations. Then, we will use frequency maps to count the amount of correct digits placed in incorrect locations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Setup:\n - We will use two frequency maps `f1` and `f2` to keep track of digits that don\'t line up between the two strings.\n2. Loop 1: Correct digits placed in correct locations\n - Remember that guess.size() == secret.size(), so we can iterate over both strings simultaneously with a for loop.\n - In this for loop, we are checking if the digits in both strings are the same and if they are in the same location.\n - We do this using `secret[i] == guess[i]`.\n - We keep track of the amount of correct digits in the correct locations using an `x` variable.\n - If this condition is not satisfied, we should keep track of how many digits are seen in each string using the two frequency maps.\n3. Loop 2: Correct digits placed in incorrect locations\n - Now that we have filled our frequency maps with values that are not fully correct, we can further calculate which digits are just incorrectly placed.\n - The condition is: check if both frequency tables contain the same digit. Then, take the minimum of the two frequency tables to get the amount of digits they have in common.\n - We can use the `y` to keep track of the amount of shared digits across the frequency tables.\n4. Termination:\n - To wrap up, we can simply build the string using our `x` and `y` variables.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n> We are performing 2 traversals of the string of size `n`, one to build the frequency tables and one to interpret the frequency tables. O(2n) simplifies to O(n)\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n> We are using 2 frequency tables of size `n`, where `n` is the size of `guess`, so O(2n) simplifies to O(n).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n // x number of correctly positioned digits\n // y number of correctly chosen digits\n\n int x = 0;\n int n = secret.size();\n unordered_map<char, int> f1;\n unordered_map<char, int> f2;\n for (int i = 0; i < n; ++i) {\n if (secret[i] == guess[i]) {\n x++;\n }\n else {\n f1[secret[i]]++;\n f2[guess[i]]++;\n }\n }\n\n int y = 0;\n for (auto item : f2) {\n if (f1[item.first] != 0 && item.second != 0) {\n y += min(f1[item.first], item.second);\n }\n }\n\n string ans = to_string(x) + \'A\' + to_string(y) + \'B\';\n\n return ans;\n }\n};\n``` | 3 | 0 | ['Hash Table', 'String', 'Counting', 'C++'] | 0 |
bulls-and-cows | C++ ✅ Commented | HashTable | c-commented-hashtable-by-taranum_01-2ew5 | \n# Approach\n1. Iterate through the characters of both the secret and guess strings.\n2. For each character:\n a. If the characters at the same index in both | Taranum_01 | NORMAL | 2024-08-12T10:56:49.892866+00:00 | 2024-08-12T12:05:40.964003+00:00 | 549 | false | \n# Approach\n1. Iterate through the characters of both the secret and guess strings.\n2. For each character:\n a. If the characters at the same index in both strings match, it\'s a bull (correct digit and position).\n b. If they don\'t match, keep track of the frequency of digits in both secret and guess.\n3. After the first pass, compare the frequency counts of the digits to determine the number of cows.\n Cows are counted by taking the minimum of the frequency counts for each digit.\n4. Finally, construct the result string in the format "{bulls}A{cows}B".\n\n\n# Complexity\n- Time complexity: O(n)\nWe traverse the strings twice, once to count bulls and track the frequency, and once to count cows.\n- Space complexity: O(1)\nWe use two fixed-size arrays of size 10 (for the digits 0-9), so the space used is constant.\n\n# Code\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n \n int bulls = 0; // Count of bulls\n int cows = 0; // Count of cows\n \n // Frequency arrays for digits 0-9\n vector<int> s(10, 0); // Frequency of digits in secret\n vector<int> g(10, 0); // Frequency of digits in guess\n \n // First pass: Count bulls and store the frequency of non-bull digits\n for (int i = 0; i < secret.length(); i++) {\n if (secret[i] == guess[i]) {\n bulls++; // Correct digit and correct position\n } else {\n s[secret[i] - \'0\']++; // Increment the frequency for the digit in secret\n g[guess[i] - \'0\']++; // Increment the frequency for the digit in guess\n }\n }\n \n // Second pass: Count cows\n for (int i = 0; i < 10; i++) {\n cows += min(s[i], g[i]); // Cows are the minimum frequency of each digit in both secret and guess\n }\n \n // Construct the result string\n string res = "";\n res += to_string(bulls) + \'A\' + to_string(cows) + \'B\';\n \n return res; // Return the result in the format "{bulls}A{cows}B"\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
bulls-and-cows | 🐮 Simple hashmap solution | Python | simple-hashmap-solution-python-by-rhuang-mo1s | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nfrom collections import Counter\nclass Solution:\n def getHint(self, secret: str | rhuang53 | NORMAL | 2024-07-26T02:55:11.795251+00:00 | 2024-07-26T02:55:11.795280+00:00 | 580 | false | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n bulls = 0\n cows = 0\n\n char_freq = Counter(secret)\n\n for i in range(len(guess)):\n if guess[i] == secret[i]:\n if char_freq[secret[i]] == 0:\n cows-=1\n char_freq[secret[i]] = 1\n char_freq[secret[i]]-=1\n bulls+=1\n elif guess[i] in char_freq and char_freq[guess[i]] > 0:\n cows+=1\n char_freq[guess[i]]-=1\n \n return str(bulls) + "A" + str(cows) + "B"\n``` | 3 | 0 | ['Hash Table', 'String', 'Counting', 'Python', 'Python3'] | 0 |
bulls-and-cows | Beats 100 % users space comlexity 0(1), time complexity 0(n) and dry run example ✅✅💯💯 | beats-100-users-space-comlexity-01-time-xv3qj | Intuition\n Describe your first thoughts on how to solve this problem. \nThe first thought will come to your mind of counting then after that of using a map bu | pahadi_rawat | NORMAL | 2024-01-11T18:50:10.552555+00:00 | 2024-01-12T09:13:02.367519+00:00 | 213 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought will come to your mind of counting then after that of using a map but if we see the question smartly we will find that extra space needed is almost negligible because we have to check digits which are in the form of string and we have only 10 digits in number system from 0 to 9 so only that much space will be required and the reason why we take minimum from both the array during cow count is explained below and bullCount is normal that if we find same val in both string then it will be definetly a bull .\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe goal of the Bulls and Cows game is to provide feedback on the player\'s guess. The code breaks down the comparison between the secret number and the guessed number into two steps:\n\n1-Counting Bulls (Correct Digit in Correct Position):\na- Iterate through each digit in the secret and guessed numbers simultaneously.\nb- If the digit in the current position is the same in both numbers, it\'s a bull. Increment the bullCount.\nc- This step ensures that we count the digits that are correctly guessed and in the correct position.\n\n2-Counting Cows (Correct Digit in Wrong Position):\na- If the digits are not bulls (not in the correct position), update counts for each digit in separate arrays (arr1 and arr2).\nb- arr1 keeps track of the count of digits in the secret number (excluding bulls).\nc- arr2 keeps track of the count of digits in the guessed number (excluding bulls).\nd- After processing all digits, count the cows by summing the minimum count of each digit in arr1 and arr2.\n\nBy taking the minimum of arr1[i] and arr2[i] for each digit i, we are essentially counting how many times a digit appears in both arr1 and arr2. This ensures that we don\'t overcount common digits; we only count them as cows if there are matching digits in both the secret and guessed numbers.\n\nFor example, let\'s say arr1[3] is 2 (meaning digit 3 appears twice in the secret number in the wrong positions), and arr2[3] is 1 (meaning digit 3 appears once in the guessed number in the wrong positions). The minimum of arr1[3] and arr2[3] is 1, indicating that there is one common digit 3 in the wrong position, contributing to the count of cows.\n\n# Complexity\n- Time complexity:0(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(12) == 0(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Example Dry Run\nexample -1\nstring 1 = 1807\nstring 2 = 7810\n\nin first loop we can detect that only 8 is common in both string therefore one BullCount =1 and we will also update both the count arrays.\n\nidx - 0 1 2 3 4 5 6 7 8 9\nsecret- 1 1 0 0 0 0 0 1 0 0 \nguess - 1 1 0 0 0 0 0 1 0 0 \n\nNow from the second loop we will get the cowcounts which will be 3.\ntherefore solution will be -> 1A3B. \n\n\n\n\n\nexample -2\nstring1 = 1122\nstring2 = 2211\n\nnow we can clearly see that none character is matching at any index so bull count =0;\nand the both the array will be\nidx - 0 1 2 3 4 5 6 7 8 9\nsecret- 0 2 2 0 0 0 0 0 0 0 \nguess - 0 2 2 0 0 0 0 0 0 0 \n\ncowCount will be minimum from both array same index which will be 4\n\noutput will be 0A4B\n\n\n# Code\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int n=secret.size();\n int bullCount=0;\n int cowCount=0;\n vector<int>secret(10,0);\n vector<int>guess(10,0);\n\n for(int i = 0; i < n; i++) {\n if(secret[i] == guess[i]) {\n bullCount++;\n }\n else {\n int x = secret[i] - \'0\';\n int y = guess[i] - \'0\';\n secret[x]++;\n guess[y]++;\n }\n }\n\n for (int i = 0; i < 10; i++) {\n cowCount+= min(secret[i],guess[i]);\n }\n\n string ans="";\n ans+=to_string(bullCount)+"A" +to_string(cowCount) +"B";\n return ans;\n }\n};\n``` | 3 | 0 | ['Hash Table', 'String', 'Counting', 'C++'] | 1 |
bulls-and-cows | Easy to understand C++ code !! Beginner Friendly | easy-to-understand-c-code-beginner-frien-hso6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n1. Initialize an unorde | khaderitesh | NORMAL | 2023-10-07T04:28:50.200640+00:00 | 2023-10-07T04:28:50.200668+00:00 | 334 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an unordered_map m to store the frequency of each digit in the secret string.\n2. Initialize bulls and cows counters to 0 to keep track of the number of bulls and cows.\n3. Iterate through each digit in the strings secret and guess simultaneously.\n4. If the digits at the same position in both strings match, increment the bulls counter.\n5. If they don\'t match, check if the current digit in secret has occurred before in the guess string. If it has, increment the cows counter and decrement its frequency in the m map.\n6. Also, check if the current digit in guess has occurred before in the secret string. If it has, increment the cows counter and decrement its frequency in the m map.\n7. After processing both strings, build the result string as follows: to_string(bulls) + \'A\' + to_string(cows) + \'B\'.\n8. Return the result string as the output.\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 getHint(string secret, string guess) {\n unordered_map<char,int>m;\n for(int i=0;i<secret.size();i++){\n m[secret[i]]++;\n }\n int bulls=0;\n for(int i=0;i<secret.size();i++){\n if(secret[i]==guess[i]){\n bulls++;\n }\n }\n int count=0;\n for(int i=0;i<guess.size();i++){\n if(m[guess[i]]==0){\n count++;\n }else{\n m[guess[i]]--;\n }\n }\n cout<<count;\n return to_string(bulls)+ \'A\' + to_string(secret.size()-bulls-count)+\'B\';\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
bulls-and-cows | C++ Solution using Map | O(n) | c-solution-using-map-on-by-lakshmi_prabh-j74b | Intuition\nShould find the number of bulls and cows. Can be solved by iterating over secret and guess, and comparing the characters. The comparison to be made f | lakshmi_prabha | NORMAL | 2023-05-02T15:33:30.547001+00:00 | 2023-05-05T11:13:11.044700+00:00 | 597 | false | # Intuition\nShould find the number of *bulls* and *cows*. Can be solved by iterating over $$secret$$ and $$guess$$, and comparing the characters. The comparison to be made for *bull* count and the *cow* count is different.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. we loop through each digit in the $$secret$$ and $$guess$$ strings, comparing the digits at the same position. If they are the same, it means that a *bull* has been found, and the digit is replaced by the character \'o\' in both the strings to mark it as a *bull*. The count of *bulls* found so far is incremented.\n2. we initialise unordered map to store the count of each digit in both the $$secret$$ and $$guess$$ strings. The map stores a pair of integers, where the first integer represents the count of the digit in the secret string, and the second integer represents the count of the digit in the guess string.\n3. The character \'o\' (which represents *bulls*) can be removed from the map as we do not it for *cows* counting.\n4. we then loop through each character in the map, adding the minimum count of the character in both the $$secret$$ and $$guess$$ strings to the variable *cows*, which represents the number of *cows* (correctly guessed digits in the wrong position).\n5. Now, we have number of *bulls* and number of *cows*. Format the $$hint$$ as "<#bulls>A<#cows>B"\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe overall time complexity of the function is O(n + k), \nSince, the strings contain only digits, maximum possible value of k is 10, which can considered to be constant.\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe unordered map $$char\\_count$$ takes space proportional to k. \n\nwhere n is the length of the $$secret$$ string and k is the number of unique digits in the $$secret$$ and $$guess$$ strings.\nThe number of unique digits is at most 10 (since the digits are from 0 to 9) and k can be considered as constant.\n\n# Code\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int secret_size = secret.size();\n int bulls = 0;\n string hint = "";\n for(int i = 0; i < secret_size; i++)\n if(secret[i] == guess[i]) {\n secret[i] = guess[i] = \'o\';\n bulls++;\n }\n hint += to_string(bulls);\n hint.push_back(\'A\');\n\n unordered_map<char,pair<int,int>> char_count;\n for(int i = 0; i < secret_size; i++) {\n char_count[secret[i]].first++;\n char_count[guess[i]].second++;\n }\n char_count.erase(\'o\');\n\n int cows = 0;\n for(auto [theChar, theCount]: char_count)\n cows += min(theCount.first, theCount.second);\n hint += to_string(cows);\n hint.push_back(\'B\');\n\n return hint;\n \n }\n};\n```\n | 3 | 0 | ['Hash Table', 'String', 'Counting', 'C++'] | 0 |
bulls-and-cows | Java Solution | Beats 100% 🔥| O(n)✅ | java-solution-beats-100-on-by-ayushmangl-sxyn | UPVOTE \u2B06\uFE0F\uD83D\uDD1D\u2B06\uFE0F\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 | ayushmanglik2003 | NORMAL | 2023-04-22T08:34:48.798142+00:00 | 2023-04-22T08:34:48.798174+00:00 | 374 | false | # UPVOTE \u2B06\uFE0F\uD83D\uDD1D\u2B06\uFE0F\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 {\n public String getHint(String secret, String guess) {\n int secdigs[] = new int[10];\n int guessdigs[] = new int[10];\n int bull = 0, cow = 0;\n\n for(int i = 0; i < secret.length() ; i ++) {\n if(secret.charAt(i) == guess.charAt(i)) {\n bull ++;\n }\n else {\n secdigs[secret.charAt(i) - \'0\'] ++;\n guessdigs[guess.charAt(i) - \'0\'] ++;\n }\n }\n\n for(int i = 0; i < 10; i ++) {\n int minVal = secdigs[i];\n if(minVal > guessdigs[i]) minVal = guessdigs[i];\n \n cow += minVal;\n }\n\n StringBuilder sb = new StringBuilder();\n sb.append(bull).append("A").append(cow).append("B");\n\n return sb.toString();\n }\n}\n``` | 3 | 0 | ['Hash Table', 'String', 'Counting', 'Java'] | 0 |
bulls-and-cows | Java. Bulls and Cows | java-bulls-and-cows-by-red_planet-x2ys | \n\nclass Solution {\n public String getHint(String secret, String guess) {\n StringBuilder first = new StringBuilder(secret);\n StringBuilder | red_planet | NORMAL | 2023-04-03T09:29:33.237204+00:00 | 2023-04-03T09:29:33.237237+00:00 | 3,105 | false | \n```\nclass Solution {\n public String getHint(String secret, String guess) {\n StringBuilder first = new StringBuilder(secret);\n StringBuilder second = new StringBuilder(guess);\n HashMap<Character, Integer> dict = new HashMap<>();\n int numA = 0;\n int numB = 0;\n for (int i = secret.length() - 1; i > -1; i--)\n {\n if (first.charAt(i) == second.charAt(i)) {\n numA++;\n first.deleteCharAt(i);\n second.deleteCharAt(i);\n }\n else {\n if (!dict.containsKey(secret.charAt(i)))\n dict.put(secret.charAt(i), 0);\n dict.put(secret.charAt(i), dict.get(secret.charAt(i)) + 1);\n }\n }\n for (int i = 0; i < second.length(); i++)\n {\n if(dict.containsKey(second.charAt(i)) && dict.get(second.charAt(i)) > 0)\n {\n numB++;\n dict.put(second.charAt(i), dict.get(second.charAt(i)) - 1);\n }\n }\n return numA + "A" + numB + "B";\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
bulls-and-cows | Easiest C++ solution | Intuition explained | w/ comments | easiest-c-solution-intuition-explained-w-5btn | Intuition\nWe need to keep track of only two conditions:\n1. Either the position of a character in both the string is same.(bull++), Or\n2. The position of a ch | arshikamishra | NORMAL | 2023-03-29T20:01:27.111576+00:00 | 2023-04-19T19:26:59.639253+00:00 | 1,872 | false | # Intuition\nWe need to keep track of only two conditions:\n1. Either the position of a character in both the string is same.(bull++), Or\n2. The position of a character is different but it is present in both the strings(cow++)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n--> We can simply have a loop to count the characters that are same (and have same index...if that makes sense).\n\n--> Then we can take an array of size 10 as there are only digits(0-9) in the string or for simplicity we can take an unordered map to count the total common characters (including cow as well as bull).\n \n--> Now we need to realize that for finding cows(same charcters but different index in the string) we can:\n no. of cows = total common characters - no. of bulls.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) [as the size of array or map can be maximum 10]\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# **If you liked the solution please UPVOTE!!**\n# Code\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) \n {\n int n=guess.size();\n\n unordered_map<int,int> m;\n for(int i=0;i<n;i++) //frequency map\n {\n m[secret[i]]++;\n }\n int b=0;\n int c=0;\n\n for(int i=0;i<n;i++) \n {\n if(secret[i]==guess[i]) // condition 1: same characters at same index\n {\n b++;\n }\n }\n \n for(int i=0;i<n;i++) //to find total no. of common characters\n {\n if(m.find(guess[i])!=m.end()) \n {\n c++;\n m[guess[i]]--;\n if(m[guess[i]]==0) // if frequency of character=0, remove the character\n {\n m.erase(guess[i]);\n }\n }\n }\n // cout<<c<<b;\n c=c-b; // no. of cows = total common characters - no. of bulls. \n string ans;\n ans=to_string(b)+"A"+to_string(c)+"B";\n return ans;\n }\n};\n``` | 3 | 0 | ['Hash Table', 'Counting', 'C++'] | 0 |
bulls-and-cows | Solution in C++ | solution-in-c-by-ashish_madhup-kt1f | 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 | ashish_madhup | NORMAL | 2023-02-24T13:05:37.341235+00:00 | 2023-02-24T13:05:37.341279+00:00 | 475 | 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 getHint(string secret, string guess) {\n int n = secret.length();\n map<char,int> mp;\n for(int i=0 ; i<n ; ++i) mp[secret[i]]++;\n int bulls = 0;\n int cows = 0;\n for(int i=0 ; i<n ; ++i){\n if(secret[i] == guess[i]){\n ++bulls;\n if(mp[guess[i]] == 1) mp.erase(guess[i]);\n else mp[guess[i]]--; \n guess[i] = \'*\';\n }\n } \n for(int i=0 ; i<n ; ++i){\n if(guess[i] != \'*\'){\n if(mp.find(guess[i]) != mp.end()){\n ++cows;\n if(mp[guess[i]] == 1) mp.erase(guess[i]);\n else mp[guess[i]]--;\n }\n }\n } \n string ans = to_string(bulls) + "A" + to_string(cows) + "B";\n return ans;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
bulls-and-cows | ✅ C++ || Beats 100% || Easy to understand || Beginner friendly | c-beats-100-easy-to-understand-beginner-1iimm | Intuition\nThere will be 3 cases at index i of the string:\n1. the characters of both string are same, then bull will be incremented by 1\n2. the characters of | codecommander03 | NORMAL | 2023-02-15T12:45:50.119563+00:00 | 2023-02-15T12:45:50.119605+00:00 | 183 | false | # Intuition\nThere will be 3 cases at index i of the string:\n1. the characters of both string are same, then bull will be incremented by 1\n2. the characters of both strings are different but character present in guess string at index is occuring elsewhere(let\'s say index j, but character in secret string at index j should be different from character in guess string at index j)\n3. the characters of both strings are different and the character in guess string doesn\'t occur in string secret;\n\n# Approach\n- As every index contains a single digit character, so max number of unique characters are 10 (0-9), so a vector to store frequency is initialized`vector<int> v(12,0);`\n- First we traverse throught the correct string storing the frequency of the character only if characters in both strings are different\n`if(secret[i]!=guess[i]) v[stoi(secret[i])]++;`\n- then we traverse throught the guess function,\n 1. case1, then increment bull`if(guess[i]==secret[i]) bull++;`\n 2. case2,\n ```\n if(v[stoi(guess[i])]>0){\n cow++;\n v[stoi(guess[i])]--;\n }\n ```\n here we are decreasing the count by 1, as repetition is not allowed\n 3. case3, no change in value of bull or cow\n\nusing `to_string()` function convert from integer to string \nAlso,\n```\nint stoi(char c){\n return int(c)-47;\n }\n``` \nis a function which reduces the value of ASCII charactr by 47\nASCII OF 0 = 47\nSo, stoi(\'5\') = 52\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int stoi(char c){\n return int(c)-47;\n }\n string getHint(string secret, string guess) {\n vector<int> v(12,0);\n int bull=0,cow=0;\n for(int i=0;i<secret.size();i++){\n if(secret[i]!=guess[i]) v[stoi(secret[i])]++;\n }\n for(int i=0;i<guess.size();i++){\n if(guess[i]==secret[i]) bull++;\n else{\n if(v[stoi(guess[i])]>0){\n cow++;\n v[stoi(guess[i])]--;\n }\n }\n }\n string s="";\n s+=to_string(bull);\n s+="A";\n s+=to_string(cow);\n s+="B";\n return s;\n }\n};\n``` | 3 | 0 | ['String', 'Counting', 'Hash Function', 'C++'] | 0 |
bulls-and-cows | JAVA || HASHMAP SOLUTION || EASY | java-hashmap-solution-easy-by-sauravmeht-5ppz | Upvote if you understand !!\n# Code\n\nclass Solution {\n class Pair{\n int val;\n List<Integer> list;\n Pair(int val,List<Integer> list | Sauravmehta | NORMAL | 2023-01-09T05:33:41.369050+00:00 | 2023-01-09T05:33:41.369099+00:00 | 1,521 | false | **Upvote if you understand !!**\n# Code\n```\nclass Solution {\n class Pair{\n int val;\n List<Integer> list;\n Pair(int val,List<Integer> list){\n this.val=val;\n this.list=list;\n }\n }\n public String getHint(String secret, String guess) {\n int A = 0;\n int B = 0;\n Map<Character,Pair> map = new HashMap<>();\n int length = guess.length();\n for(int i=0;i<length;i++){\n if(map.containsKey(secret.charAt(i))){\n Pair p = map.get(secret.charAt(i));\n p.val++;\n p.list.add(i);\n }\n else{\n map.put(secret.charAt(i),new Pair(1,new ArrayList<Integer>()));\n Pair p = map.get(secret.charAt(i));\n p.list.add(i);\n }\n }\n \n char[] ch = guess.toCharArray();\n for(int i=0;i<ch.length;i++){\n if(map.containsKey(ch[i]) && map.get(ch[i]).list.contains(new Integer(i))){\n map.get(ch[i]).val--;\n ch[i]=\'-\';\n A++;\n }\n }\n\n for(int i=0;i<ch.length;i++){\n if(ch[i] != \'-\' && map.containsKey(ch[i]) && map.get(ch[i]).val> 0){\n map.get(ch[i]).val--;\n B++;\n }\n }\n return A+"A"+B+"B";\n }\n}\n\n``` | 3 | 0 | ['Java'] | 0 |
bulls-and-cows | Microsoft⭐ || Easy Solution✔️ || Challenge🏆 | microsoft-easy-solution-challenge-by-nan-yjbe | "Your thoughts are welcome! \uD83D\uDCAD"\n\n#ReviseWithArsh #6Companies30Days challenge 2k23 & 2k24*\nCompany 2 :- Microsoft\n\nDay1 - Q2. Bulls and Cows\n\n\n | nandini-gangrade | NORMAL | 2023-01-03T21:09:13.952236+00:00 | 2024-01-12T12:33:05.156805+00:00 | 413 | false | > ***"Your thoughts are welcome! \uD83D\uDCAD"***\n\n***```#ReviseWithArsh #6Companies30Days challenge 2k23 & 2k24```**\n**`` Company 2 :- Microsoft ``***\n\n*Day1 - Q2. Bulls and Cows*\n\n\n\n### Code\n```cpp []\nclass Solution {\npublic:\n // Function to calculate the hint for the secret and guess strings\n string getHint(string secret, string guess) {\n // Initialize counters for bulls and cows\n int bulls = 0;\n int cows = 0;\n\n // Create arrays to store the frequency of digits in secret and guess\n vector<int> s(10, 0); // s[i] stores the frequency of digit i in the secret\n vector<int> g(10, 0); // g[i] stores the frequency of digit i in the guess\n\n // Iterate through the characters of secret and guess\n for (int i = 0; i < secret.length(); i++) {\n // Check for bulls (correct digit and position)\n if (secret[i] == guess[i]) {\n bulls++;\n } else {\n // If not a bull, update the frequency of digits in secret and guess\n s[secret[i] - \'0\']++;\n g[guess[i] - \'0\']++;\n }\n }\n\n // Calculate the number of cows by finding the minimum frequency for each digit\n for (int i = 0; i < 10; i++) {\n cows += min(s[i], g[i]);\n }\n\n // Build the result string\n string ans = "";\n ans += to_string(bulls); // Append the number of bulls\n ans += \'A\';\n ans += to_string(cows); // Append the number of cows\n ans += \'B\';\n\n // Return the final hint\n return ans;\n }\n};\n```\n*Let\'s collaborate! Join me on GitHub to work on this challenge together* :- \n*[https://github.com/nandini-gangrade/6Companies30Days](GITHUB)*\n\n> ***Happy Coding \uD83D\uDCBB***\n | 3 | 0 | ['C++'] | 0 |
bulls-and-cows | [Java] 2ms, 99% + clear explanations | java-2ms-99-clear-explanations-by-stefan-xhkh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Traverse the two strings and keep track of the digits count in 2 x int | StefanelStan | NORMAL | 2022-12-07T21:22:45.091556+00:00 | 2022-12-07T21:22:45.091610+00:00 | 472 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Traverse the two strings and keep track of the digits count in 2 x int[10]\n2. While traversing, if current secret digit matches guess digit, only increment the bulls, but do not mark the digit count. This is because we ignore the bulls.\n3. Traverse both count arrays and return the sum of their mins. (cows)\nEG: \n - If secret has 7 0s and guess has 3 0s, means only the 3 zeroes can be moved around\n - If secret has 3 0s but guess has 7 0s, you can only shuffle and match the 3 0s.\n - Thus, only the min between the two is taken in consideration\n4. Return the formatted string containing bulls and cows. \n\n\n# Complexity\n- Time complexity:$$O(n) + O(10)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(20)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String getHint(String secret, String guess) {\n int[] secretCount = new int[10];\n int[] guessCount = new int[10];\n int bulls = 0;\n char sChar, gChar;\n for (int i = 0; i < secret.length(); i++) {\n sChar = secret.charAt(i);\n gChar = guess.charAt(i);\n if (sChar == gChar) {\n bulls++;\n } else {\n secretCount[sChar - \'0\']++;\n guessCount[gChar - \'0\']++;\n }\n }\n int cows = 0;\n for (int i = 0; i < secretCount.length; i++) {\n cows += Math.min(secretCount[i], guessCount[i]);\n }\n return new StringBuilder().append(bulls).append(\'A\').append(cows).append(\'B\').toString();\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
bulls-and-cows | Single passing solution | single-passing-solution-by-lavkush_173-wxt6 | public String getHint(String secret, String guess) {\n int bulls = 0;\n int cows = 0;\n int[] numbers = new int[10];\n for (int i = 0; i<secret.leng | Lavkush_173 | NORMAL | 2022-11-23T17:33:14.608076+00:00 | 2022-11-23T17:33:14.608114+00:00 | 221 | false | public String getHint(String secret, String guess) {\n int bulls = 0;\n int cows = 0;\n int[] numbers = new int[10];\n for (int i = 0; i<secret.length(); i++) {\n if (secret.charAt(i) == guess.charAt(i)) bulls++;\n else {\n if (numbers[secret.charAt(i)-\'0\']++ < 0) cows++;\n if (numbers[guess.charAt(i)-\'0\']-- > 0) cows++;\n }\n }\n return bulls + "A" + cows + "B";\n} | 3 | 0 | [] | 0 |
bulls-and-cows | Python | O(N) | Dictionary Count | EZ solution | python-on-dictionary-count-ez-solution-b-bs7f | class Solution(object):\n def getHint(self, secret, guess):\n \n bulls, cows = 0, 0\n lenN = len(secret)\n \n secDic = { s | CosmosYu | NORMAL | 2022-10-18T00:17:56.117155+00:00 | 2022-10-18T00:17:56.117185+00:00 | 151 | false | class Solution(object):\n def getHint(self, secret, guess):\n \n bulls, cows = 0, 0\n lenN = len(secret)\n \n secDic = { str(i) : [0 , 0] for i in range(10)}\n \n for i in range(lenN):\n \n if(secret[i] == guess[i]):\n bulls += 1\n \n secDic[secret[i]][0] += 1\n secDic[guess[i]][1] += 1\n \n for i in range(10):\n cows += min(secDic[str(i)])\n \n return str(bulls) + \'A\' + str(cows - bulls) + \'B\'\n \n \n \n | 3 | 0 | [] | 1 |
bulls-and-cows | C++ SIMPLE SOLUTION USING MAP | c-simple-solution-using-map-by-abhay_123-xsnj | \nclass Solution {\npublic:\n string getHint(string &secret, string &guess) {\n int c = 0, b = 0, i = 0, n = secret.length();\n unordered_map<c | abhay_12345 | NORMAL | 2022-10-11T17:27:53.407544+00:00 | 2022-10-11T17:27:53.407589+00:00 | 822 | false | ```\nclass Solution {\npublic:\n string getHint(string &secret, string &guess) {\n int c = 0, b = 0, i = 0, n = secret.length();\n unordered_map<char,char> mp;\n for(i = 0; i < n; i++){\n if(secret[i]==guess[i]){\n b++;\n guess[i] = \'#\';\n }else{\n mp[secret[i]]++;\n }\n }\n for(auto &i: guess){\n if(i != \'#\' && mp.count(i) && mp[i]>0){\n c++;\n }\n mp[i]--;\n }\n return to_string(b)+\'A\'+to_string(c)+\'B\';\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
bulls-and-cows | Swift Clean Easy Solution | swift-clean-easy-solution-by-jfrsheriff-kqsi | \nclass Solution {\n func getHint(_ secret: String, _ guess: String) -> String {\n\t\n guard secret.count == guess.count else {return ""}\n \n | jfrsheriff | NORMAL | 2022-10-09T15:34:06.951394+00:00 | 2022-10-09T15:34:27.360590+00:00 | 138 | false | ```\nclass Solution {\n func getHint(_ secret: String, _ guess: String) -> String {\n\t\n guard secret.count == guess.count else {return ""}\n \n var secretA = Array(secret)\n var guessA = Array(guess)\n \n var sDict : [Character : Int] = [:]\n var gDict : [Character : Int] = [:]\n \n var bulls = 0\n var cows = 0\n \n // Finding Bulls\n for i in 0..<secretA.count {\n if secretA[i] == guessA[i] {\n bulls += 1 \n }else{\n sDict[secretA[i],default:0] += 1\n gDict[guessA[i],default:0] += 1\n }\n }\n \n // Finding Cows\n for (key,val) in sDict{\n let minVal = min(gDict[key,default:0],val)\n cows += minVal\n }\n return "\\(bulls)A\\(cows)B"\n\t\t\n }\n}\n``` | 3 | 0 | ['Swift'] | 0 |
bulls-and-cows | O(N) time | on-time-by-droj-lcvx | \nclass Solution:\n def getHint(self, se: str, gu: str) -> str:\n dcse=defaultdict(lambda:0)\n dcgu=defaultdict(lambda:0)\n a=0\n | droj | NORMAL | 2022-09-29T12:29:27.699600+00:00 | 2022-09-29T12:29:27.699634+00:00 | 561 | false | ```\nclass Solution:\n def getHint(self, se: str, gu: str) -> str:\n dcse=defaultdict(lambda:0)\n dcgu=defaultdict(lambda:0)\n a=0\n b=0\n for i in range(len(se)):\n if(se[i]==gu[i]):\n a+=1\n else:\n dcse[se[i]]+=1\n dcgu[gu[i]]+=1\n for x in dcse:\n if(dcgu[x]>=dcse[x]):\n b+=dcse[x]\n else:\n b+=dcgu[x]\n return(str(a)+"A"+str(b)+"B")\n``` | 3 | 0 | ['Python'] | 1 |
bulls-and-cows | ✅✅Faster || Easy To Understand || C++ Code | faster-easy-to-understand-c-code-by-__kr-yspj | Using Unordered Map\n\n Time Complexity :- O(N)\n\n Space Complexity :- O(N)\n\n\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n | __KR_SHANU_IITG | NORMAL | 2022-08-09T12:27:46.182139+00:00 | 2022-08-09T12:27:46.182189+00:00 | 226 | false | * ***Using Unordered Map***\n\n* ***Time Complexity :- O(N)***\n\n* ***Space Complexity :- O(N)***\n\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n \n int n = secret.size();\n \n // count the frequency of characters of secret\n \n unordered_map<char, int> mp;\n \n int bulls = 0;\n \n int cows = 0;\n \n for(int i = 0; i < n; i++)\n {\n if(secret[i] == guess[i])\n {\n bulls++;\n }\n else\n {\n mp[secret[i]]++;\n }\n }\n \n // count the no. of cows\n \n for(int i = 0; i < n; i++)\n {\n if(secret[i] != guess[i])\n {\n if(mp[guess[i]] > 0)\n {\n cows++;\n \n mp[guess[i]]--;\n }\n }\n }\n \n return to_string(bulls) + "A" + to_string(cows) + "B";\n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
bulls-and-cows | Easy C++ Code using Map | easy-c-code-using-map-by-karan252-c43f | \nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n map<char,int> mp;\n int n=secret.size();\n int b=0,c=0;\n | karan252 | NORMAL | 2022-07-05T19:45:35.480592+00:00 | 2022-07-05T19:45:35.480668+00:00 | 382 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n map<char,int> mp;\n int n=secret.size();\n int b=0,c=0;\n for(int i=0;i<n;i++)\n {\n if(secret[i]==guess[i])\n b++;\n else\n mp[secret[i]]++;\n }\n for(int i=0;i<n;i++)\n {\n if(secret[i]!=guess[i] && mp.find(guess[i])!=mp.end())\n {\n c++;\n mp[guess[i]]--;\n if(mp[guess[i]]==0)\n mp.erase(guess[i]);\n }\n }\n string ans=to_string(b)+"A"+to_string(c)+"B";\n return ans;\n \n }\n};\n``` | 3 | 0 | ['C', 'C++'] | 0 |
bulls-and-cows | C++ | HASING | COUNTING | FASTER | c-hasing-counting-faster-by-harshsinghs1-wotk | \nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int n = secret.size(), a[10] = {0},b[10] = {0},bulls = 0,cows = 0;\n | UnknownOffline | NORMAL | 2022-07-01T02:29:35.979546+00:00 | 2022-07-01T02:29:35.979576+00:00 | 221 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n int n = secret.size(), a[10] = {0},b[10] = {0},bulls = 0,cows = 0;\n for(int i = 0;i<n;i++)\n if(secret[i] == guess[i]) bulls++;\n else{\n a[secret[i] - \'0\']++;\n b[guess[i] - \'0\']++;\n }\n for(int i = 0;i<10;i++) cows += min(a[i],b[i]);\n return to_string(bulls) + \'A\' + to_string(cows) + \'B\';\n }\n \n};\n```\n\n | 3 | 0 | ['C', 'Counting'] | 0 |
bulls-and-cows | Python beats 100% | python-beats-100-by-kungfupanda30-jeyt | Python solution using Counter\n```from collections import Counter\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n a=0\n | kungfupanda30 | NORMAL | 2022-01-24T07:44:55.720966+00:00 | 2022-01-24T07:45:22.866301+00:00 | 241 | false | Python solution using Counter\n```from collections import Counter\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n a=0\n for i,j in zip(secret,guess):\n if (i==j):\n a+=1\n k=Counter(secret)\n l=Counter(guess)\n return "%dA%dB" % (a, sum((k & l).values()) - a) | 3 | 0 | ['Python'] | 1 |
bulls-and-cows | C++|| 0 ms || Easy to Understand | c-0-ms-easy-to-understand-by-tejas03-l2sw | Iterate over the string,\nif secret char == guess char then bull++\notherwise, increase freq of respective char\'s.\nFor cow -\nIterate over the freq and count | Tejas03 | NORMAL | 2021-07-02T11:29:55.124926+00:00 | 2021-07-02T11:29:55.124964+00:00 | 123 | false | Iterate over the string,\nif secret char == guess char then bull++\notherwise, increase freq of respective char\'s.\nFor cow -\nIterate over the freq and count of every digit will be min(secret Freq, guess Freq)\n\n```\nclass Solution {\npublic:\nstring getHint(string secret, string guess) {\nint bull = 0;\n// Frequency of secret digits\nvector secFreq(10,0);\n// Frequency of guess digits\nvector gueFreq(10,0);\nfor(int i = 0; i < secret.size();i++){\nif(secret[i] == guess[i])bull++;\nelse {\nsecFreq[secret[i] - \'0\']++;\ngueFreq[guess[i] - \'0\']++;\n}\n}\n\n\t// For cows\n int cow = 0;\n for(int i = 0;i < 10;i++){\n cow += min(secFreq[i],gueFreq[i]);\n }\n return to_string(bull) + \'A\' + to_string(cow) + \'B\';\n}\n}; | 3 | 1 | ['C', 'C++'] | 1 |
bulls-and-cows | c++ simple solution | c-simple-solution-by-fangfang_qf-o275 | \nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n //count bulls first \n int bulls = 0, cows = 0;\n vector<i | fangfang_qf | NORMAL | 2020-12-21T03:10:21.187621+00:00 | 2020-12-21T03:10:21.187660+00:00 | 216 | false | ```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n //count bulls first \n int bulls = 0, cows = 0;\n vector<int> sMap(10, 0);\n vector<int> gMap(10, 0);\n \n for (int i = 0; i < guess.size(); i++) {\n if (secret[i] == guess[i]) {\n bulls++; \n } else {\n sMap[secret[i] - \'0\']++;\n gMap[guess[i] - \'0\']++;\n } \n }\n for (int i = 0; i < 10; i++) {\n cows += min(sMap[i], gMap[i]);\n }\n return to_string(bulls) + \'A\' + to_string(cows) + \'B\';\n }\n};\n``` | 3 | 0 | ['C'] | 0 |
bulls-and-cows | Java | Beats 100% | Runtime- 1ms | Use only Array | java-beats-100-runtime-1ms-use-only-arra-nu6l | \nclass Solution {\n public String getHint(String secret, String guess) {\n char [] s = secret.toCharArray();\n char [] g = guess.toCharArray() | abideenzainuel | NORMAL | 2020-09-11T01:40:55.347626+00:00 | 2020-09-11T01:43:12.456655+00:00 | 246 | false | ```\nclass Solution {\n public String getHint(String secret, String guess) {\n char [] s = secret.toCharArray();\n char [] g = guess.toCharArray();\n \n int [] count = new int[10];\n int a = 0;\n int b = 0;\n \n StringBuffer sb = new StringBuffer();\n\n for(int i=0; i<s.length; i++){\n if(s[i] == g[i]){\n g[i] = \'*\';\n a++;\n }else{\n count[s[i]-\'0\']++;\n }\n }\n \n for(int i=0; i<g.length; i++){\n if(g[i] != \'*\' && count[g[i]-\'0\'] > 0){\n count[g[i] - \'0\']--;\n b++;\n }\n }\n \n return sb.append(a).append("A").append(b).append("B").toString();\n \n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
bulls-and-cows | Python Two Pass - 20ms | python-two-pass-20ms-by-ragav_1302-xzbd | \nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n a=0\n b=0\n for i,j in zip(secret,guess):\n if i==j: | ragav_1302 | NORMAL | 2020-09-10T12:34:05.289060+00:00 | 2020-09-10T12:34:41.699117+00:00 | 135 | false | ```\nclass Solution:\n def getHint(self, secret: str, guess: str) -> str:\n a=0\n b=0\n for i,j in zip(secret,guess):\n if i==j:\n a+=1 \n secret=secret.replace(i,\'*\',1)\n guess=guess.replace(i,\')\',1)\n for j in guess: \n if j in secret:\n b+=1 \n secret=secret.replace(j,\'*\',1)\n return str(a)+"A"+str(b)+"B"\n```\n\nRuntime: 20 ms, faster than 100.00% of Python3 online submissions for Bulls and Cows.\nMemory Usage: 13.7 MB, less than 93.70% of Python3 online submissions for Bulls and Cows. | 3 | 0 | [] | 0 |
bulls-and-cows | C++ || 99.43% || Simple || Using Vector | c-9943-simple-using-vector-by-priyanshi4-trrw | The solution goes like\n Compare strings to find bulls\n Save the numbers that could be found as cows (i.e. all except the bulls)\n* Compare the guess with the | priyanshi417 | NORMAL | 2020-09-10T12:23:31.755003+00:00 | 2020-09-10T12:23:39.852429+00:00 | 229 | false | The solution goes like\n* Compare strings to find bulls\n* Save the numbers that could be found as cows (i.e. all except the bulls)\n* Compare the guess with the possible cows, to get total cows\n\n```\nclass Solution {\npublic:\n string getHint(string secret, string guess) {\n \n string ret;\n int num=0;\n \n //for bulls\n for(int i=0; i<secret.size()&&i<guess.size(); i++)\n {\n if(secret[i]==guess[i])\n num++;\n }\n ret.append(to_string(num));\n ret.push_back(\'A\');\n num=0;\n \n //for cows\n vector<int> sec(10, 0);\n for(int i=0; i<secret.size(); i++)\n {\n if(i<guess.size()&&(guess[i]!=secret[i]))\n sec[secret[i]-\'0\']++;\n }\n \n for(int i=0; i<guess.size(); i++)\n {\n if(sec[guess[i]-\'0\']&&guess[i]!=secret[i])\n {\n sec[guess[i]-\'0\']--;\n num++;\n }\n }\n \n ret.append(to_string(num));\n ret.push_back(\'B\');\n \n return ret;\n \n }\n};\n``` | 3 | 0 | ['C'] | 1 |
bulls-and-cows | Efficicient C++ Solution | Comments | Faster than 99% | efficicient-c-solution-comments-faster-t-ubf1 | \nclass Solution {\npublic:\n int pairs(string str1, string str2, int size){\n // Counting the frequency of numbers in str1 and str2.\n int f1[ | ansh_srtv | NORMAL | 2020-09-10T11:21:07.323462+00:00 | 2020-09-11T09:30:56.876909+00:00 | 438 | false | ```\nclass Solution {\npublic:\n int pairs(string str1, string str2, int size){\n // Counting the frequency of numbers in str1 and str2.\n int f1[10] = { 0 };\n int f2[10] = { 0 };\n int i, c = 0;\n \n for (i = 0; i < size; i++)\n f1[str1[i] - \'0\']++;\n \n for (i = 0; i < size; i++)\n f2[str2[i] - \'0\']++;\n \n // Counting common characters in the strings.\n for (i = 0; i < 10; i++)\n c += (min(f1[i], f2[i]));\n \n return c;\n }\n string getHint(string secret, string guess) {\n int a=0,b,n = secret.size();\n \n b=pairs(secret,guess,n); // Common characters \n \n for(int i=0;i<n;i++) // Common characters with correct positions.\n if(secret[i]==guess[i])\n a++;\n \n // b contains all the common characters, so removing bulls.\n string res=to_string(a)+\'A\'+to_string(b-a)+\'B\'; \n return res;\n }\n};\n```\n* Upvote if you like this solution.\n* Open for discussion. | 3 | 0 | ['C'] | 1 |
minimize-the-difference-between-target-and-chosen-elements | [Python] 4 lines solution, explained | python-4-lines-solution-explained-by-dba-kdsp | The idea is that our numbers are very small: mat[i][j] <= 70, and also m, n <= 70. It means, tha final sum of all numbers can be no more than 70**2.\n\nSo, we c | dbabichev | NORMAL | 2021-08-22T04:00:44.068219+00:00 | 2021-08-22T05:21:44.730556+00:00 | 9,901 | false | The idea is that our numbers are very small: `mat[i][j] <= 70`, and also `m, n <= 70`. It means, tha final sum of all numbers can be no more than `70**2`.\n\nSo, we can do almost bruteforce solution: iterate over rows and keep in `nums` all possible sums we get so far.\n\n#### Complexity\nEach time we have in `nums` no more than `70**2` elements and we travere it not more than `70` rows, each of which have no more than `70` elements so final complexity is `O(n^4)`, where `n = 70`. Then we need to find closes element to target which is just `O(n^3)`. Space complexity is `O(n^3)`. It was **AC** during contest for me, however now it gives TLE.\n\n```python\nclass Solution:\n def minimizeTheDifference(self, mat, target):\n nums = {0}\n for row in mat:\n nums = {x + i for x in row for i in nums}\n \n return min(abs(target - x) for x in nums)\n```\n\n#### Solution 2\nWe can optimize solutoin, taking into account that we need to look around `target`. That is if minimal sum of all numbers is more than target, we do no have choice: we need to take it. In the opposite case no need to go higher than `2*target - possible_min`\n\n#### Complexity\nTime complexity is `O(target * n^2)` now, space is `O(target)`.\n\n#### Code\n```python\nclass Solution:\n def minimizeTheDifference(self, mat, target):\n possible_min = sum(min(row) for row in mat)\n if possible_min > target: return possible_min - target\n \n nums = {0}\n for row in mat:\n nums = {x + i for x in row for i in nums if x + i <= 2*target - possible_min}\n \n return min(abs(target - x) for x in nums)\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**\n | 131 | 10 | [] | 39 |
minimize-the-difference-between-target-and-chosen-elements | DP + Pruning, 4Sum II and All Sums | dp-pruning-4sum-ii-and-all-sums-by-votru-ipl5 | Approach 1: DP + Pruning\n\nThe sum of the entire matrix cannot be larger than 70 * 70. We can use this fact for memoisation.\n\nNow, to achieve good runtime (t | votrubac | NORMAL | 2021-08-22T04:32:20.195933+00:00 | 2021-08-22T21:25:01.817461+00:00 | 12,360 | false | #### Approach 1: DP + Pruning\n\nThe sum of the entire matrix cannot be larger than 70 * 70. We can use this fact for memoisation.\n\nNow, to achieve good runtime (the code below is ~80 ms), we need to sort each row and remove duplicates. \n- This way, we can stop after the running sum exceeds the target.\n\n> Update. Test cases are week, and thanks [sandyleo26](https://leetcode.com/sandyleo26/), [louisfghbvc](https://leetcode.com/louisfghbvc/) and [nate17](https://leetcode.com/nate17/) for examples. The original pruning was too complicated and did not pass stronger test cases.\n\n**C++**\n```cpp\nint dp[71][70 * 70 + 1] = {[0 ... 70][0 ... 70 * 70] = INT_MAX};\nint dfs(vector<set<int>>& m, int i, int sum, int target) {\n if (i >= m.size())\n return abs(sum - target);\n if (dp[i][sum] == INT_MAX)\n for (auto it = begin(m[i]); it != end(m[i]); ++it) {\n dp[i][sum] = min(dp[i][sum], dfs(m, i + 1, sum + *it, target));\n if (dp[i][sum] == 0 || sum + *it > target)\n break;\n }\n return dp[i][sum];\n}\nint minimizeTheDifference(vector<vector<int>>& mat, int target) {\n vector<set<int>> m;\n for (auto &row : mat)\n m.push_back(set<int>(begin(row), end(row)));\n return dfs(m, 0, 0, target);\n}\n```\n\n#### Approach 2: 4Sum II\nThis problem is similar to [4Sum II](https://leetcode.com/problems/4sum-ii/), with the difference that we need to return the closest sum, not necessarily the exact one.\n\nFor that approach, we collect sums for upper and lower parts of the matrix independently. Then, we go through the first set of sums, and binary search for a compliment in the second set of sums. See an example code [here](https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/discuss/1418651/c++-bitset.-meh.../1057516).\n\n#### Approach 3: All Sums\nAgain, since the max sum is limited to 70 * 70, we could compute all possible sums and then search for the closest one.\n\nUsing a hash set in C++, however, is too slow (TLE). So I am using a bit array, and tracking max element so far to not to scan all 70 * 70 elements every time.\n\n**C++**\n```cpp\nint minimizeTheDifference(vector<vector<int>>& mat, int target) {\n bool bt[70 * 70 + 1] = {};\n int max_e = 0, res = INT_MAX;\n for (auto & row : mat) {\n bool bt1[70 * 70 + 1] = {};\n int max_e1 = 0;\n for (auto i : unordered_set(begin(row), end(row))) {\n for (int j = 0; j <= max_e; ++j)\n if (j == max_e || bt[j]) {\n bt1[i + j] = true;\n max_e1 = max(max_e1, i + j);\n }\n }\n swap(bt, bt1);\n max_e = max_e1;\n }\n for (int i = 0; i <= 70 * 70; ++i) {\n if (bt[i])\n res = min(res, abs(i - target));\n }\n return res;\n}\n``` | 112 | 3 | [] | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.