Given two strings, write a method to decide if one is a permutation of the other

Problem

Given two strings, write a method to decide if one is a permutation of the other.

Example) 

Given two strings, "mom", "grandmom", your algorithm should return True because "mom" is the permutation of "grandmom".


String comparison using the HashTable, $O(N)$

The brute force approach can be checking each string is the other permutation by generating the permutations of one string and checking the other word exists in the permutation.

This takes $O(N \times N!)$ for each case, which is terribly inefficient.

Can we do better? Of course, we can !!

Say we are given two words, "mom" and "grandmom". We know instantly that grandmom can't be the permutation of "mom" since the former is short than the latter.

How do we know "mom" is the permutation of "grandmom"?

As long as all the characters of "mom" exist in "grandmom" we can say that there is one permutation that is the same as "mom".

Using Hash Table, we can record the occurrence of the characters consisting of each word. The hash table for the short word, $H_s$ and the one for the longer word, $H_l$.

Once this is done, we can check if all the characters of the shorter word exist in the longer word as follows:

      Check the occurrence count of chars in the short words in $H_s$ $\le$ the occurrence count of chars in $H_l$. In expression,

     { $\forall c$  $\in$ $S_1$, $H_s$[c] <= $H_l$[c] }

The overall running time of this algorithm will be $O(N)$, where N is the length of the longer string.

C++ solution

Python solution
Practice statistics

20:00 mins: to write up the code and test the code

UPDATE(2022-06-13): It turned out that we don't need to create the hashtable for the shorter one. We can just iterate over the shorter word and check if the character exists in the longer one's hashtable and decrement for each occurrence, Code is way shorter.

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the maximum number of bomb that can be detonated