The current setup, A and B could be larger anagrams but I chose a simple example here.
The goal is to find an index mapping P, from A to B. A mapping P[i] = j means the [n]th element in A appears in B at index j.
const A = [12, 28, 46, 32, 50]
const B = [50, 12, 32, 46, 28]
const hash = B.reduce((acc,cur,idx) => ({ ...acc, [cur]: idx }), {});
const result = A.reduce((acc,cur) => [...acc, hash[cur]], []);
return result
The result should be
[1, 4, 3, 2, 0]
What I think the time/space complexity for my solution is:
hash: time = O(a), space = O(c)
result: time = O(b), space = O(d)
Final answer is time = O(a + b), space = O(c + d)
Final final answer for time and space is O(n)?
Even though the result is being generated using time O(1) because of the hash, overall I think the time is O(n) cause n is the numbers. Am I correct in thinking this?
What is everyone thought on this? (If I'm right or wrong, not sure).
I figured some of you would ask why not use indexOf(), from my research, it looks like under the hood its a loop so I would be running O(2n). So medium to large size anagrams would be fatal.