LeetCode299BullsandCows
You are playing the following bull and cow game with your friend: you write down a number and ask your friend to guess what the number is. Whenever your friend guesses, you provide a hint as to how many of the digits in said guess match your password exactly, including the number and location (called a "bull") and how many digits match the password but are in the wrong location (called a "cow"). Write a function that returns a hint based on a secret number and a friend's guess, for A for bull and B for cow.
Example 1:
importation: secret = "1807", guess = "7810" exports: "1A3B" Description: 1 bull and 3 cows. Bulls are 8, cows are 0, 1 and 7.
Example 2:
importation: secret = "1123", guess = "0111" exports: "1A1B" instructions: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
At first my idea was to get the number of bulls and cows in order, but the cow decision requires O(n^2) time complexity, then I thought, using the number of all matches - the number of bulls is the number of cows, which only requires O(n) time complexity and O(1) space complexity.
public String getHint(String secret, String guess) { int[] table = new int[10]; int total = 0; int bulls = 0; for (char c :secret.toCharArray()) { table[c - '0']++; } for (int i = 0; i < guess.length(); i++) { if (secret.charAt(i) == guess.charAt(i)) { bulls++; } if (table[guess.charAt(i) - '0']-- > 0) { total++; } } return bulls + "A" + (total - bulls) + "B"; }
Runtime: 1 ms, faster than 100.00% of Java online submissions for Bulls and Cows.