Array-based Java Solution


  • 0
    O
    • Iterate through the characters of the strings using a single cursor.
    • If the chars at a position are the same, increment bull.
    • Else increment the frequency of the char in it's respective frequency array.
    • Iterate through the frequency arrays using a single pointer and sum up the minimums to get the cows.

    Runtime complexity: O(n). Space complexity: O(1).

    public class Solution {
      public String getHint(String secret, String guess) {
        int[] secretArr = new int[10], guessArr = new int[10];
        int bull = 0, cow = 0;
        for (int a = 0; a < secret.length(); a++) {
          if (secret.charAt(a) == guess.charAt(a)) bull++;
          else {
            secretArr[secret.charAt(a) - '0']++;
            guessArr[guess.charAt(a) - '0']++;
          }
        }
            
        for (int a = 0; a < secretArr.length; a++) cow += Math.min(secretArr[a], guessArr[a]);
        return String.format("%dA%dB", bull, cow);
      }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.