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?