Solving HackerRank Problem: Anagram using Java

Problem

Two words are anagrams of one another if their letters can be rearranged to form the other word. In this challenge, you will be given a string. You must split it into two contiguous substrings, then determine the minimum number of characters to change to make the two substrings into anagrams of one another.

Complete the anagram function in the editor below. It should return the minimum number of characters to change to make the words anagrams, or -1 if it's not possible.

See the full description of the problem Anagram

Solution

  • Get frequency of first and second half
  • Count the changes second half needs to become first half

Time complexity: O(n)  //Time equivalent to input size

Space complexity: O(1) //The alphabet is limited to 26 char so maps have a constant size

Credit: @github.com/RyanFehr