Skip to content

Latest commit

 

History

History
47 lines (31 loc) · 1.22 KB

File metadata and controls

47 lines (31 loc) · 1.22 KB

Level: Medium

Topic: String Hash Table Counting

Similar Problem:

Question

You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Intuition

The goal of this problem is to find out the difference in charcters in s and t.

  • since it's the anagram of both, their length must be same
  • use freq char array to count the difference in characters

Code

Time: O(n+m)
Space: O(26) = O(1)

public int minSteps(String s, String t) {
    int [] freq = new int[26];
    int diff = 0;

    for (char c: s.toCharArray())
        freq[c-'a']++;

    for (char c: t.toCharArray()) {
        freq[c-'a']--;
        if (freq[c-'a'] < 0)
            diff++;
    }

    return diff;
}