Postmates | OA 2020 | Close Strings
3177

We will consider two strings close if one can be obtained from the other, using the following operations:

swap any two symbols in one of the strings,
swap occurrences of any two existing symbols in one of the strings (for example, if your string contains both as and bs, you can change all as to bs and all the bs to as).
Now you want to write a method that finds out whether the given strings are considered close, by the definition above.

Example

For A = "abbzccc" and B = "babzzcz", the output should be
closeNames(A, B) = true.

One possible way to transform "abbzccc" to "babzzcz" is this:

"abbzccc" (this string is className)
"babzccc" (swap positions of the first two characters)
"babczzz" (switch all c and z characters)
"babzzcz" (swap positions of the characters at indices 3 and 5; this string is now methodName)

For A = "abcbdb" and B = "bbbcca", the output should be closeNames(A, B) = false.

**My Solution: **

I created a map of char frequencies for both the strings & calculated the frequency differences. But the solution couldnt pass some hidden test cases.

boolean closeNames(String A, String B) {
        if (A.length() != B.length())
            return false;
        Map<Character, Integer> mp1 = new HashMap<>(), mp2 = new HashMap<>();
        int i = 0;

        for (i = 0; i < A.length(); i++) {
            mp1.put(A.charAt(i), mp1.getOrDefault(A.charAt(i), 0) + 1);
            mp2.put(B.charAt(i), mp2.getOrDefault(B.charAt(i), 0) + 1);
        }

        int tot = 0, val1, val2;
        for (char key: mp1.keySet()) {
            val1 = mp1.get(key);
            if (!mp2.containsKey(key))
                return false;
            else {
                val2 = mp2.get(key);
                if (val1 != val2)
                    tot += (val1 - val2);
            }
        }

        return tot == 0? true:false;
    }
Comments (11)