I'm currently studying for a technical interview and I'm just going through the leetcode grind. I came across a question that is apparently asked pretty frequently by the company I'm about to interview at so I attempted it. I couldn't quite get it so I looked to the solution and came across this solution.
var merge = function(intervals) {
if(!intervals.length) return intervals;
intervals = intervals.sort((a,b) => a[0] - b[0])
let prev = intervals[0];
let res = [prev];
for(let curr of intervals){
if(curr[0] <= prev[1]){
prev[1] = Math.max(prev[1], curr[1]);
} else {
res.push(curr);
prev = curr;
}
}
return res;
};
on line 5, res is set to equal [prev], which in this case is [1,3] so
res = [[1,3]]
for now.
Then as the code progresses, notice how the value of prev is updated. I thought this was weird since res is never updated at all, but by updating the value of prev, the prev inside res is also updated. My question is:
How does updating the value of prev update the value of the prev that's inside res? I thought I was going crazy so I tested it and this solution worked. I thought that once the prev inside res has been assigned, it would be immutable? Am I missing something here?
CodePudding user response:
let prev = intervals[0];
let res = [prev];
At this point, res[0]
, prev
, and intervals[0]
all have the same value.
console.log(prev === res[0]); // true
console.log(prev === intervals[0]); // true
console.log(res[0] === intervals[0]); // true
If this value were referencing an object, then they all point at the object. If you were to reassign prev
, that does not modify res[0]
, nor intervals[0]
.
prev = 'something else';
console.log(prev === res[0]); // FALSE
console.log(prev === intervals[0]); // FALSE
console.log(res[0] === intervals[0]); // true
How does updating the value of prev update the value of the prev that's inside res?
You can see by this example that updating the value of prev
does not actually update the value of res[0]
.
However, updating the value of prev[1]
is actually updating the value of index 1
of the object/array that prev
references. In other words, you're not changing prev
by setting prev[1] =
... you're changing prev[1]
, which is the same as res[0][1]
.
CodePudding user response:
It doesn't make sense to you because you're assuming that a new copy of prev
is being created when you do res = [prev]
.
Instead, try to think of it this way: an array gets created which internally points to the memory address of the data that prev
contains. Whenever data in that memory address changes, it will be updated everywhere that address was used.
I would read up about reference types vs primitive types.
CodePudding user response:
This happens because prev
's reference is being pointed by res
when you do res=[prev]
, basically the address where the actual prev
array is stored is pointed, as the prev updates, it also show changes in res.