Given two strings, write a function to determine if the first string is a permutation of the second.
Note
You won’t be dealing with permutation validation this often in real life, don’t worry! However, this is a good exercise in finding duplicate occurrences.
There are two ways to go about this. One that optimizes runtime on account of space and the other that optimizes for space. This is always a great point to start a discussion with your interviewer to understand what we’re aiming for.
Time complexity
O(nlogn)
Sorting string and one loop over string.
Space complexity
O(1)
Constant amount of auxillary variables used.
Note
O(n)
, but this is language specific. Make sure to mention this to your interviewer!This works! But can we do better?
If both strings hold identical chars, they are a permutation of one another, regardless of the order! Let’s use an auxillary data structure to document characters seen and their occurrences. If all chars appear equally we know we have a palindrome!
Time complexity
O(n)
Loop over input once
Space complexity
O(n)
Constant amount of auxillary variables used.
When dealing with strings and permutations we can try and use the common techniques of:
Cracking the Coding Interview (CTCI) 1.2
Quick Links
Legal Stuff