0

I was looking at this solution here

Finding anagrams for a given word

Also if it helps here is the interview question

An anagram is a rearrangement of the letters in a given string into a sequence of dictionary words, like Steven Skiena into Vainest Knees. Propose an algorithm to construct all the anagrams of a given string.

What is the time complexity of this? Is this a valid backtracking algoirthm or is this more taking advantage of space to create a solution?

I am looking at the solution from Daniel, and that looks like it may take up a lot of space with a tree?

My real question though is, if I was asked this on an interview, what time of explanation do I give? A pseudo code answer or a real program?

Community
  • 1
  • 1
Chieve
  • 57
  • 6
  • Depends what you want to do. Identify a words as anagram of another word (like in the provided link) or generate a list of all anagrams of a word (as proposed in your question). – Paul Dec 17 '16 at 23:14
  • Alright thanks! Was going for the question specifically but thought the response in the link was interesting and gave good direction :) – Chieve Dec 17 '16 at 23:43

1 Answers1

0

A real solution probably takes too long to write in an interview. Here is how you can implement the back-tracking part. It's just pseudo-code:

function getAnagrams(str) {
  helper('', str.replace(' ', '').toLowerCase().sort());
}

function helper(prefix, str) {
  foreach (word in dictionary) {
    if (word.isShuffleOf(str)) {
      solution.add(prefix == '' ? word : prefix + ' ' + word);
    } else if (str.contains(word)) {
      helper(prefix == '' ? word : prefix + ' ' + word, str.subtract(word));
    }
  }
}
maraca
  • 7,323
  • 3
  • 20
  • 41