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?
2
Answers
One approach here is to copy
arrayB
into aMap
from each element’sconstructor
to its value. Then we can iterate overarrayA
‘s elements and for each one, if itsconstructor
is a key in theMap
we 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
arrayA
and b is the length ofarrayB
, assuming that operations on aMap
are 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 iteratingarrayB
for each element ofarrayA
(e.g.,arrayA.map(a => arrayB.find(⋯)
) , which would be O(a×b).And because apparently you want
arrayB
to be mutated, we can cleararrayB
after 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
arrayB
ends up with instances ofObject1
,Object2
, andObject3
in that order, but only theObject3
constructor gets invoked; theObject1
andObject2
instances fromarrayB
are re-used.Identify the classes present in
arrayA
that are not inarrayB
. Using thefilter()
onarrayA
, check if each class is included inarrayB
, if not, add it to a new array and create new instances of these classes and add them toarrayB
. Add variablemissingClasses
, this contains the classes that are inarrayA
but not inarrayB
, and use it to create the new instances. Then, make sure that the objects inarrayB
are in the same order as inarrayA
.