Let's say I have 2 arrays each of which holds a few different objects
class Object1 {}
class Object2 {}
class Object3 {}
class Object4 {}
class Object5 {}
class Object6 {}
const arrayA = [
new Object1(),
new Object2(),
new Object3()
]
const arrayB = [
new Object4(),
new Object1(),
new Object2(),
new Object6()
]
I need to mutate arrayB so that it holds instances of the same classes as arrayA in the same order.
But I need to reuse any instances in arrayB of classes that are also present in arrayA.
The desired output here would be:
arrayB = [
instanceOfObject1AlreadyInArrayB,
instanceOfObject2AlreadyInArrayB,
new Object3()
]
How would you solve this with the best possible big O notation?
Are there any comparable algorithm names I can research?
One approach here is to copy
arrayBinto aMapfrom each element'sconstructorto its value. Then we can iterate overarrayA's elements and for each one, if itsconstructoris a key in theMapwe use the existing value, otherwise we construct a new instance.The time complexity of this is essentially just O(a+b) where a is the length of
arrayAand b is the length ofarrayB, assuming that operations on aMapare constant-time O(1). Technically the spec only requires that it be sublinear, so then all we can say for sure is that the time complexity of the whole process is strictly less than O((a+b)2), so at the least it scales better than iteratingarrayBfor each element ofarrayA(e.g.,arrayA.map(a => arrayB.find(⋯)) , which would be O(a×b).And because apparently you want
arrayBto be mutated, we can cleararrayBafter copying its contents to theMap, and then just push the elements onto it. This is O(a) and thus doesn't affect the overall time complexity.Here is an example:
If you run that snippet you'll see that
arrayBends up with instances ofObject1,Object2, andObject3in that order, but only theObject3constructor gets invoked; theObject1andObject2instances fromarrayBare re-used.