0

how do you create a reverse lookup array in an efficient way?

e.g. [5, 3, 1, 4, 2] => [3, 5, 2, 4, 1]

Obviously a simple way is:

const input = [5, 3, 1, 4, 2];
const output = [];
for (i = 0; i < input.length; i++) {
    output[input[i] - 1] = i + 1;
}
1
  • btw, why not take the indices instead of one based value which requires always an offset? Commented Nov 3, 2021 at 9:47

1 Answer 1

2

Your method is O(n): I don't think that can be beaten

You do have to go across every element in the input (to read it) and every element of the output (to write it): there is no getting out of that!

My only suggestion to slightly speed it up is to pre-size the output array.

const input = [5, 3, 1, 4, 2];
const output = new Array(input.length);
input.forEach(
  (value, i) => output[value - 1] = i + 1
)

console.log(output)

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks. Is it possible to just use the input and swap items within without creating another array?
For lurkers: While it's true that JavaScript arrays are sparse by nature and in theory (per spec), all "pre-sizing" the array does is set length, in fact modern JavaScript engines do take that length into account. V8, for instance, allocates memory for that many elements even though they start out empty.
I don't think it is possible to do it without using at least some additional space. Even if you tried the principle of "this one needs to move to THAT position, so let's kick out the one at THAT position next...", you might end up with cycles, without having covered them all. If you try to cover them all systematically, i.e. in order, you will run out of places to keep the ones that need to move.
@Eureka it is possible, by creating a reversed iterator instead.
Hi @vitaly - Can you add as a full answer? Myself, I can't see how a reversed iterator would help. I have no objection to my answer being de-accepted and a new one accepted, and am always keen to learn.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.