Java solution with explanation


  • 0
    L

    The problem is simple but it has lots of edge conditions that may make your solution fail(like it happened to me). However, the simple idea is to do the bulls first and then cows. This is required to make sure that you don't count and exhaust out of place characters (depending on your algorithm). This algorithm does 2 passes: first pass to match bulls and also stores the count of unmatched values inside a hashmap. The 2nd pass is simply running over unmatched values and count cows.

    public String getHint(String secret, String guess) {
            final Map<Character,Integer> map = new HashMap<>();
            char[] arr = guess.toCharArray();
            int bulls=0;
            for(int i=0;i<secret.length();i++) {
                if(secret.charAt(i)==arr[i]){
                    //bulls.
                    bulls++;
                    arr[i]='A';
                }
                else {
                    int val = map.getOrDefault(secret.charAt(i),0);
                    map.put(secret.charAt(i),++val);
                }
            }
    
            int cows=0;
            for(int i=0;i<arr.length;i++) {
                if(arr[i]!='A') {
                    int val = map.getOrDefault(arr[i],0);
                    if(val>0) {
                        cows++;
                        map.put(arr[i],--val);
                    }
                }
            }
    
            return bulls + "A" + cows + "B";
        }
    

Log in to reply
 

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