Microsoft Interview Question

Given a string, find whether it has any permutation of another string. Need to be efficient

Interview Answers

Anonymous

Mar 8, 2013

public boolean test(String main, String sub){ char[] a = main.toCharArray(); char[] b = sub.toCharArray(); char[] c = sub.toCharArray(); Arrays.sort(b); for(int i = 0; i

1

Anonymous

Feb 27, 2013

isnt it enough if we find out whether the characters in the second string is present in the first? (also the number of times each character appears).?

Anonymous

Feb 27, 2013

The characters need to be consecutive. For example, if the second string is "abc", we need to find out whether the first string has one of the following: "abc" , "acb" , "bac" , "bca" , "cab" or "cba"

Anonymous

Mar 2, 2013

I think this is what you can do: public bool IsPermutation(string source, string permutation) { //convert string to array of chars char[] sourceChars = source.toCharArr(); char[] permutationChars = permutation.toCharArr(); int[] sourceCounts = new int[256]; //assume ASCII, 256 chars //loop through all chars in source for(int i = 0; i < sourceChars.length; i++) { int charIndex = sourceChars[i] - 'a'; //make 0 based index sourceCounts[charIndex]++; //increment value on that index } //loop through all in permutation for(int i = 0; i < permutationChars.length; i++) { int charIndex = permutationChars[i] - 'a'; if(--sourceCounts[charIndex] < 0) //there's not enough characters in source return false; } return true; } I hope that this helps!