I do have a problem, that I am trying to use the most efficient way to solve it.
"Given two strings, find out if the two strings are permutation of each other."
I do know the straightforward ways to do it (i.e sorting the two strings) etc.
I want to see if my approach will work for all cases, and I am not sure, so I need your opinion and your input.
def CheckPermutaionsBySumUp(firstString, secondString):
if (len(firstString) != len(secondString)):
return False
firstStringCount = 0
secondStringCount = 0
for char in firstString:
firstStringCount += ord(char)
for char in secondString:
secondStringCount += ord(char)
if firstStringCount == secondStringCount:
return True
return False
So my approach is that, I do have a constraint that helps here, and is that if the two strings are not of the same length, then the two strings are not permutation of each other.
Then, knowing that each character has a unique number representation, if I sum up the number of each letter for each string using the ord
function, I can then compare the two sums and find out if the two strings are permutation. This solution, in my opinion is not only O(n) but also is really space-efficient, than using arrays and data-structures.
My only concern, is there any chance that two strings, with the same length, and with different characters to have the same summation?