Remove cycle from Object | SDE2 & SDE3 | JavaScript Interview Question - 12

preview_player
Показать описание
JavaScript Interview Question - 12 | In this video, we will see how to solve a JavaScript problem where we are given a circular object and we are asked to remove the circle.

Get my Ebook "JavaScript Interview Guide" with 120+ solved JavaScript questions.

Social links
Рекомендации по теме
Комментарии
Автор

Hi Prashant, solved it on my own. My Practise of LinkedList Helped.

//Below is my solution
class List {
constructor(val) {
this.next = null;
this.val = val;
}
}

const item1 = new List(10);
const item2 = new List(20);
const item3 = new List(30);

item1.next = item2;
item2.next = item3;
item3.next = item1;

const removeCycle = (node) => {
visited = new Set()
let curr = node
while(curr && curr.next){
if(visited.has(curr.next)){
curr.next = null
}else{
visited.add(curr)
}
curr = curr.next
}
return node
}


//Output - {"next":{"next":{"next":null, "val":30}, "val":20}, "val":10}

akash-kumar
Автор

Can we apply fast and slow pointer approach

abhinaisai
Автор

Hi prashanth
In first method, in else condition i think there is no need to add store.add(obj[key]) right?
Any how we are adding all the elements in starting only and weakset will only take unique values

deepakheerakari
Автор

Great explaination. I have question here. why we are assigning Weakset with [obj] instead of leaving it as empty constructor?

PraveenKumar-xdix
visit shbcf.ru