Skip to content

Commit 391e54c

Browse files
committed
Add solution #299
1 parent b651426 commit 391e54c

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@
244244
292|[Nim Game](./0292-nim-game.js)|Easy|
245245
295|[Find Median from Data Stream](./0295-find-median-from-data-stream.js)|Hard|
246246
297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard|
247+
299|[Bulls and Cows](./0299-bulls-and-cows.js)|Medium|
247248
300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium|
248249
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
249250
306|[Additive Number](./0306-additive-number.js)|Medium|

solutions/0299-bulls-and-cows.js

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 299. Bulls and Cows
3+
* https://leetcode.com/problems/bulls-and-cows/
4+
* Difficulty: Medium
5+
*
6+
* You are playing the Bulls and Cows game with your friend.
7+
*
8+
* You write down a secret number and ask your friend to guess what the number is.
9+
* When your friend makes a guess, you provide a hint with the following info:
10+
* - The number of "bulls", which are digits in the guess that are in the correct position.
11+
* - The number of "cows", which are digits in the guess that are in your secret number but
12+
* are located in the wrong position. Specifically, the non-bull digits in the guess that
13+
* could be rearranged such that they become bulls.
14+
*
15+
* Given the secret number secret and your friend's guess guess, return the hint for your
16+
* friend's guess.
17+
*
18+
* The hint should be formatted as "xAyB", where x is the number of bulls and y is the number
19+
* of cows. Note that both secret and guess may contain duplicate digits.
20+
*/
21+
22+
/**
23+
* @param {string} secret
24+
* @param {string} guess
25+
* @return {string}
26+
*/
27+
var getHint = function(secret, guess) {
28+
const map = Array(10).fill(0);
29+
let a = 0;
30+
let b = 0;
31+
32+
for (const i in secret) {
33+
if (secret[i] === guess[i]) {
34+
a++;
35+
} else {
36+
map[secret[i]]++;
37+
map[guess[i]]--;
38+
b += map[secret[i]] <= 0;
39+
b += map[guess[i]] >= 0;
40+
}
41+
}
42+
43+
return `${a}A${b}B`;
44+
};

0 commit comments

Comments
 (0)