Given two numbers a, b such that 1 <= a , b <= 10000000000 (10^10). My problem is to check whether the digits in them are permutation of each other or not. What is the fastest way of doing it? I was thinks of using hashing but unable to find any suitable hash function. Any suggestions?
For e.g –
123 is a valid permutation of 312
Also I don’t want to sort the digits in the numbers.
If you mean the characters of the numbers (such as 1927 and 9721), there are (at least) a couple of approaches.
If you were allowed to sort, one approach is to simply
sprintfthem to two buffers, sort the characters in the buffers, then see if the strings are equal.However, given your desire to not sort the digits, another alternative is to set up a ten-element array, with all elements initially set to zero, then process each digit in the first number, incrementing the relevant element.
Then do the same with the second number but decrementing.
If, at the end, it’s still all zeros, the numbers were a permutation of each other.
This is efficient in that it’s an
O(n)algorithm wherenis the number of digits in the two numbers. The pseudo-code for such a beast would be something like:In C, the following complete program illustrates how this can be done:
Simply pass it two (positive) numbers and, assuming they fit in a
long, it’ll tell you whether they have the same digit counts.