Copy List with Random Pointer - Linked List - Leetcode 138

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 ต.ค. 2024

ความคิดเห็น • 168

  • @aaen9417
    @aaen9417 ปีที่แล้ว +51

    this time I figured out by myself that I would need 2 passes, 1 for the nodes creation and a second one for the linking, also I figured a hashmap would be the best way of accessing the copies. However, your solution is by far more simple and elegant. Thanks so much for inspiring us to keep practicing!

    • @jeromee-dev
      @jeromee-dev 2 หลายเดือนก่อน +1

      Haha, that's funny because I tried to do that approach where we create the nodes and add a reference to it in a dictionary in the first pass and then set each node's random property in the second pass. Unfortunately, I got a KeyError exception.

    • @jeromee-dev
      @jeromee-dev 2 หลายเดือนก่อน

      My bad again, just realized that I wasn't updating the dictionary correctly, so I can confirm that it works.

  • @MrPaulzeng
    @MrPaulzeng 3 ปีที่แล้ว +48

    NeetCode gives the best Leetcode explanations on TH-cam, imo

  • @tnmyk_
    @tnmyk_ 2 ปีที่แล้ว +21

    You were right, it's much easier to understand the solution by looking at the code than to explain it. Well done!

  • @bernardpark3196
    @bernardpark3196 3 ปีที่แล้ว +53

    Just wanted to say you are awesome, and thank you for your time and effort that you put into your videos! Much appreciated 🙏

  • @fredtrentini6791
    @fredtrentini6791 10 หลายเดือนก่อน +15

    I solved the problem with some 10x more complicated logic using the id function to uniquely identify each node by it's memory address, and from there on making a hashmap that maps the memory address to the node, all because I had no idea you could assign an object as hashmap key... feels really nice to learn that but I am definitely feeling pretty stupid right now LOL

    • @AndreiSokolov-k7j
      @AndreiSokolov-k7j 6 หลายเดือนก่อน

      in c++ to use unordered map you'll need to create own hash function for non standard objects)))

  • @Demo-man
    @Demo-man ปีที่แล้ว +5

    Your videos are great you have no idea how much you've helped me! For an alternative solution I also used a hashmap from nodes in the original list to nodes in the new list, but I was able to do this all in one pass! You can simply create the connections and create the new nodes as necessary, adding them to the hashmap. Then, if at any point when adding a connection for "next" or "random" you find that you've already created a node for the corresponding node in the original list then you can go ahead and use that pointer. Hope this helps someone!

    • @leonscander1431
      @leonscander1431 2 หลายเดือนก่อน

      Yes, I did it in one pass too as you described.

  • @sumitghewade2002
    @sumitghewade2002 ปีที่แล้ว +3

    I struggled with 3-4 Linked List questions from NeetCode list and watched and learnt from your videos. And finally was able to come up with the solution similar to yours without watching the video. Thank you. Your way of explaining algorithm is effortless. Please make a video on how to explain your thoughts about a question in an interview?

  • @ananya___1625
    @ananya___1625 2 ปีที่แล้ว +3

    I came up with very complicated solution and was amazed to see ur simple solution.Thanks a lot for your time and efforts

  • @romangirin772
    @romangirin772 ปีที่แล้ว +10

    It can be done via just _one_ traversal in recursive DFS manner
    class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    cloned = {}
    def dfs(node: 'Optional[Node]') -> 'Optional[Node]':
    if node is None:
    return None
    if node in cloned:
    return cloned[node]
    clone = Node(node.val)
    cloned[node] = clone
    clone . next = dfs(node.next)
    clone.random = dfs(node.random)
    return clone
    return dfs(head)

    • @lewisw29
      @lewisw29 ปีที่แล้ว +1

      genius

    • @abhijeetviswa
      @abhijeetviswa 3 หลายเดือนก่อน +1

      Isn't is just a recursive 2 pass solution. The second pass happens in the reverse order of items when the stacks are unwinding.
      I'd argue this is less efficent because of the additional stack space

  • @htoomyatnaing5775
    @htoomyatnaing5775 2 ปีที่แล้ว +1

    There is not a single Neetcode video that doesn't help me understand a problem. Much love and appreciation!

  • @rahulsbhatt
    @rahulsbhatt ปีที่แล้ว +1

    I was complicating this by linking the new nodes except the random and decided to link the random ptr in the next pass, but your solution eases this out, thank you so much for posting this!

  • @mrkandreev
    @mrkandreev 7 หลายเดือนก่อน +4

    You have to know that exists second solution with O(1) space. It is possible if you change input linked list with appending clonned values between existed nodes in linked list.

  • @sayanghosh6996
    @sayanghosh6996 ปีที่แล้ว +8

    this can be done in O(1) space by interleaving the old and new nodes while creating.
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    if not head: return head
    ptr = head
    while ptr:
    newnode = Node(ptr.val, ptr.next)
    ptr.next = newnode
    ptr = newnode.next
    ptr = head
    while ptr:
    ptr.next.random = ptr.random.next if ptr.random else None
    ptr = ptr.next.next
    ptr = head.next
    while ptr:
    ptr.next = ptr.next.next if ptr.next else None
    ptr = ptr.next
    return head.next

    • @AyushmanTiwari-u6o
      @AyushmanTiwari-u6o 9 หลายเดือนก่อน

      thanks man

    • @tenkara101
      @tenkara101 9 หลายเดือนก่อน

      yup never figuring this out on my own lol

    • @myhandle370
      @myhandle370 หลายเดือนก่อน

      I just thought about exactly the same approach :D

  • @lovuitchen9332
    @lovuitchen9332 3 ปีที่แล้ว +14

    Clean, concise and good, as always! Thank you!

  • @eugenevedensky6071
    @eugenevedensky6071 3 ปีที่แล้ว +7

    Cool approach. I added an index property to hash the nodes in Javascript, since attempting to hash with the node itself will lead to the key being "[object Object]" rather than the memory address as I imagine it does in python.

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +5

      That's a good idea!

    • @AdemsPerspective
      @AdemsPerspective 2 ปีที่แล้ว +3

      You could also use Map in JS. It supports objects as key.

    • @eugenevedensky6071
      @eugenevedensky6071 2 ปีที่แล้ว +2

      @@AdemsPerspective nice suggestion, I’ve found it performs better than hash map, too.

    • @ChaosB7ack
      @ChaosB7ack 2 ปีที่แล้ว +1

      If you're assigning an index you don't necessarily need to go through hashing btw, it might speed up things if you assign an array index instead and then create an array of nodes.
      This was my first intuition
      class Solution:
      def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
      curr = head
      if not curr:
      return None
      i = 0
      while curr:
      curr.v = i
      i += 1
      curr = curr.next
      curr = head
      res = []
      for n in range(i):
      res.append(Node(0))
      for n in range(i):
      res[n].next = res[n + 1] if n < i - 1 else None
      res[n].val = curr.val
      res[n].random = res[curr.random.v] if curr.random else None
      curr = curr.next
      return res[0]
      I don't love this because it relies on modifying the original and you usually don't really want to do that. Check out the weaving solution on leetcode, I think that one is the best one.

    • @eugenevedensky6071
      @eugenevedensky6071 2 ปีที่แล้ว

      @@ChaosB7ack Nice! I love getting responses to algo stuff like this way after I commented. Yeah, you're right, if you can reliably use an index it's as good as hashing basically.

  • @kushagrabansal2107
    @kushagrabansal2107 2 ปีที่แล้ว +2

    Please do more problems. I really love to watch your explanations after I give the problem a try.

  • @phantomhunter7985
    @phantomhunter7985 2 ปีที่แล้ว +7

    My mind just got blown. How was I not able to think of using a hashmap at all?

  • @meghaldarji598
    @meghaldarji598 2 ปีที่แล้ว +3

    I was scratching my head to figure out the solution for 20 mins. it's so hilarious that the solution could be something this simple! FML😂😂

  • @rockywu5502
    @rockywu5502 2 ปีที่แล้ว +3

    So simple and elegant, just wow.

  • @KarthickSubramanian-k8t
    @KarthickSubramanian-k8t ปีที่แล้ว +15

    Who would have thought this approach in thier first try? Not me..

  • @danielrodrigues4903
    @danielrodrigues4903 ปีที่แล้ว +3

    This can also be done with no extra space (besides what's needed for making the new list). It creates the nodes of the new list directly woven in-between the nodes of the original. Discovered I could do it in this way after using the Hint button on LeetCode.
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    if head is None:
    return None

    ptr = head
    while ptr:
    new = Node(ptr.val, ptr.next)
    ptr.next = new
    ptr = ptr.next.next

    ptr = head
    while ptr:
    copy = ptr.next
    copy.random = ptr.random.next if ptr.random else None
    ptr = copy.next

    ptr = head.next
    while ptr:
    ptr.next = ptr.next.next if ptr.next else None
    ptr = ptr.next

    return head.next

  • @alexshay7969
    @alexshay7969 ปีที่แล้ว +1

    Thank you Fords!! I'm not well versed in Python, but when I looked at your Java code it's very clear.

  • @GoziePO
    @GoziePO 11 หลายเดือนก่อน

    I really like this problem! Thanks for making these videos to help us all see the algorithms and thought process clearly!

  • @symbol767
    @symbol767 2 ปีที่แล้ว +3

    Wow this is such a simple and amazing explanation, thank you, liked!

  • @chenhaibin2010
    @chenhaibin2010 2 ปีที่แล้ว +1

    that is the youtuber worth its name. Thank you

  • @jiajingxie7660
    @jiajingxie7660 2 ปีที่แล้ว +2

    Hello neetcode, I am a python beginner. I am learning LeetCode through your video explanation. I can say that you are the best and most detailed explanation I have ever encountered. I am currently studying in the United States (UC san diego). I can easily understand what you mean. Thanks for the video, hope you can make more videos. (Don't be lazy!)

    • @NeetCode
      @NeetCode  2 ปีที่แล้ว +3

      Thanks, and I'll definitely continue!

  • @anonymous........
    @anonymous........ 14 วันที่ผ่านมา

    The interweaving approach can also be considered the better solution due to its O(1) space complexity while maintaining O(N) time complexity.

  • @Matt-qr2xw
    @Matt-qr2xw ปีที่แล้ว +1

    You can use O(1) space for this problem. On pass one, build next links for the new list and establish a two way relationship with the matching node from the second list by using the unused random pointer of list2 to point to list 1. You can also break the next pointer on list1 and use it to point to the list2 node. Then on pass two use those pointers to get to the random node and build the random pointers.

    • @glennquagmire9572
      @glennquagmire9572 11 หลายเดือนก่อน +2

      By creating the deep copy you will automatically have O(n) space, otherwise it would not be a copy

    • @LangePirate
      @LangePirate 11 หลายเดือนก่อน

      damn you're right XD@@glennquagmire9572

    • @ap84wrk
      @ap84wrk 10 หลายเดือนก่อน +1

      @@glennquagmire9572 the goal is to avoid extra space. Or let's say that all algorithms which must consider input as immutable have space complexity which is greater of equal to their output length.

    • @glennquagmire9572
      @glennquagmire9572 10 หลายเดือนก่อน

      @@ap84wrkWhat do you want tell me with that? If you have to create a copy you can never achieve constant space.

  • @orepajic2625
    @orepajic2625 27 วันที่ผ่านมา

    A friend of mine got asked to solve this in O(1) space by microsoft, apart from being very difficult to come up with the idea its almost impossible to explain the idea and code it up in 45 minutes (-5 for questions and 10-15 for introduction)

  • @Eda-gm7oy
    @Eda-gm7oy 2 ปีที่แล้ว +9

    I have the final round interview with Microsoft tomorrow, thank you so much for the great videos. If I pass, I will be a lifetime supporter of your channel, promise! :D

  • @mohamedantar1249
    @mohamedantar1249 10 วันที่ผ่านมา +1

    Best explanation ever❤

  • @tien-yuhsin2095
    @tien-yuhsin2095 3 ปีที่แล้ว +2

    so when copying old nodes to copy, did you copy the references to next and random?

  • @RAjat9590
    @RAjat9590 2 ปีที่แล้ว +4

    There is also one optimal solution to this which avoids the extra O(n) space of the hashmap.

    • @LangePirate
      @LangePirate 11 หลายเดือนก่อน

      True by doing 3 passes instead of 2 you get time: O(3n), space: O(1) , which simplifies to time: O(n), space: O(1), which is technically better. Hint: use the random references wisely!

    • @LangePirate
      @LangePirate 11 หลายเดือนก่อน

      actually someone pointed out that by creating a deep copy you're already at O(n) space... so rip XD

    • @ranvirchhina5179
      @ranvirchhina5179 9 หลายเดือนก่อน +1

      @@LangePirate Return value doesn't count when calculating memory complexity

  • @odysy5179
    @odysy5179 8 หลายเดือนก่อน +1

    This can actually be done in a single pass using a hashmap as well!

    • @talbenjo4841
      @talbenjo4841 7 หลายเดือนก่อน

      how? say you reached a node and its next hasnt been created yet? if you create it on the spot how do you remember to link its previous to it?

  • @wlcheng
    @wlcheng 2 ปีที่แล้ว +2

    I come up with the same idea but your code is much more concise. Great content!

  • @MsSkip60
    @MsSkip60 3 ปีที่แล้ว +5

    Would FAANG expect O(1) space solution?

    • @eugenevedensky6071
      @eugenevedensky6071 3 ปีที่แล้ว +4

      Absolutely they would, at least G and F would. They would certainly ask a follow up about how you can reduce to O(1) at the very least.

    • @chaitanyavarma2097
      @chaitanyavarma2097 2 ปีที่แล้ว +3

      fb wants it.

  • @akhma102
    @akhma102 25 วันที่ผ่านมา

    Thank you, Neet!

  • @pun1sher98
    @pun1sher98 4 วันที่ผ่านมา

    I solved this using recursive approach of building the list from last to the first node.
    Anyone else though ofthe same?
    Btw, this was the first medium problem that I solved on my own!
    Basically, the hashmap part is the same, but instead of doing 2 passes, build the list from ground up:
    Maintain a hashmap of which can map old to new nodes, as well as track if the node is already created.
    From here, try to build the list recursively by creating the 'next' and 'random' nodes of the current node.

  • @ehsank7046
    @ehsank7046 3 ปีที่แล้ว +2

    Just ran to this question on leetcode today. Thanks for the video!

  • @aishwaryaranghar3385
    @aishwaryaranghar3385 2 ปีที่แล้ว +1

    Thank You sir! Your explanations are the best!

  • @monarahmanimehr8365
    @monarahmanimehr8365 3 ปีที่แล้ว +2

    great explanation!!!

  • @ManojBaruahadams
    @ManojBaruahadams 9 หลายเดือนก่อน

    Nice explanation with pass1 and pass2.

  • @vandananayak9426
    @vandananayak9426 2 ปีที่แล้ว

    I just thanked god when I found yoursolution for this problem.

  • @NeilSharma-u5n
    @NeilSharma-u5n หลายเดือนก่อน

    i figured you would go over the interweaving node solution but oh well.

  • @priyavardhanpatel6155
    @priyavardhanpatel6155 ปีที่แล้ว

    damn bro you just killed it man..... really love your solutions. Thank you so much.

  • @gersimuca
    @gersimuca ปีที่แล้ว +2

    what does old represent?

  • @kowshiksai
    @kowshiksai 24 วันที่ผ่านมา

    In the first pass what if 2 nodes have the same values, hash map will overwrite the first one right

  • @aliciasuper7014
    @aliciasuper7014 3 ปีที่แล้ว +2

    Amazing explanation

    • @NeetCode
      @NeetCode  3 ปีที่แล้ว +2

      Happy it was helpful 🙂

  • @abigailiovino72
    @abigailiovino72 2 ปีที่แล้ว +1

    could some explain why we need to specify "None : None " ? doesn't this happen automatically when we copy the original in the first loop?

    • @khanhchung5207
      @khanhchung5207 ปีที่แล้ว

      because "next" and "random" of a node can be None. This is why he put it there for such cases. My solution in Python just used "get()" to handle these cases. Because "get()" either returns Node or None.

  • @RobinHistoryMystery
    @RobinHistoryMystery 5 หลายเดือนก่อน

    thanks,
    There is one more solution, Time: O(n), Space: O(1), with a twisted but clever logic

  • @MP-ny3ep
    @MP-ny3ep ปีที่แล้ว

    Superb Explanation !

  • @sachinkolachana6384
    @sachinkolachana6384 ปีที่แล้ว

    Thanks. Would google expect a constant memory solution for an L5/L6 SDE role?

  • @bereketyisehak5584
    @bereketyisehak5584 11 หลายเดือนก่อน

    We can also do it in one pass by creating the copy of the random node as we go.

  • @santiagolimas2014
    @santiagolimas2014 3 ปีที่แล้ว +1

    Thank you!

  • @quirkyquester
    @quirkyquester 2 ปีที่แล้ว +1

    this is a fire video brother!

  • @rohanpaul2504
    @rohanpaul2504 ปีที่แล้ว

    This is genious of a solution !!

  • @ssuriset
    @ssuriset หลายเดือนก่อน

    So, the bruteforce is the optimal? I had the same thought... hashmap. That's cool though.

  • @davidbednar7174
    @davidbednar7174 2 ปีที่แล้ว +1

    What's a worse solution?

  • @OdablockShort
    @OdablockShort 5 หลายเดือนก่อน

    In the second pass, copy just keeps getting overridden each iteration of the while loop since it's not being stored anywhere, so how is this being saved? I'm very confused with the second pass if someone could better explain to me how it works and how it's being stored.

  • @CST1992
    @CST1992 5 หลายเดือนก่อน

    This doesn't work with javascript, because it converts objects to [object Object].
    I had to add indices to each node (that is, cur) to get it to work.

  • @leul1407
    @leul1407 2 ปีที่แล้ว

    Thanks very helpful as always.

  • @CST1992
    @CST1992 5 หลายเดือนก่อน

    Man, I cannot BELIEVE it's this easy.

  • @zhe7518
    @zhe7518 6 หลายเดือนก่อน

    Is it possible to do it in one pass using a hashmap?

  • @dollyvishwakarma2
    @dollyvishwakarma2 2 ปีที่แล้ว +1

    The solution works for me only when I add additional checks if the key exists before accessing the oldToCopy which kind of makes sense to me since some node's random pointer could be None. Any thoughts?

    • @frankl1
      @frankl1 2 ปีที่แล้ว +1

      Yeah right, this is why in the video he added the pair None:None in the hashMap.

  • @yanxu9167
    @yanxu9167 2 ปีที่แล้ว +1

    very helpful, very clear! Thank you for sharing.

  • @fernandoluna5458
    @fernandoluna5458 2 ปีที่แล้ว

    Nice solution, but I have a concern about using objects as keys in our hashmap? Is it guaranteed that the hashcode is unique for each object?

  • @Wanderor1
    @Wanderor1 2 ปีที่แล้ว +1

    Hey man! This was really helpful. Thank you so much!

  • @bhagyshritech2714
    @bhagyshritech2714 2 ปีที่แล้ว

    CAN YOU MAKE SOME LIST OF QUESTION WHICH CAN COVER ALL TOPIC OF DSA ALGO for self test

  • @zechenguo9672
    @zechenguo9672 ปีที่แล้ว

    Thanks for the great explanation but I'm confused as to why we can use class objects as dictionary keys? I thought dictionary keys have to be immutable but the Node objects are mutable.

    • @pinchonalizo
      @pinchonalizo ปีที่แล้ว

      What is being used as the dict key is a reference (pointer) to memory, which is not mutable. Python uses references for non-primitive data types

  • @jacktran01
    @jacktran01 5 หลายเดือนก่อน

    One of the issues with this solution is that the class Node doesn't appear to be hashable

  • @samzzz6760
    @samzzz6760 ปีที่แล้ว

    That was written elegantly

  • @amirbayat5713
    @amirbayat5713 2 ปีที่แล้ว

    how is the list getting created though?
    cause we are updating the copy each time, without keeping a reference to its head. Help a brother out

  • @pekarna
    @pekarna 2 ปีที่แล้ว +1

    Slight speedup: In the 2nd pass, we don't need to iterate over the whole list, but rather just over a "todo list". Which may be empty and save us the whole pass.
    Runtime: 190 ms, faster than 90.91% of Kotlin online submissions for Copy List with Random Pointer.
    Memory Usage: 35.8 MB, less than 85.23% of Kotlin online submissions for Copy List with Random Pointer.

    • @hhcdghjjgsdrt235
      @hhcdghjjgsdrt235 2 ปีที่แล้ว

      I submitted the same code. first it was 35 % faster then it was 90 % faster

    • @NihongoWakannai
      @NihongoWakannai ปีที่แล้ว

      @@hhcdghjjgsdrt235 yeah, the runtime is completely random when the difference between 90% and 30% is only a few ms. It means literally nothing

  • @Prohduct
    @Prohduct 2 ปีที่แล้ว

    great explanation

  • @sahilsharma2867
    @sahilsharma2867 ปีที่แล้ว

    I thought dictionary allow only hashable objects to be stored in the key. How could a node be stored?
    edit: custom objects can be stored as key in dictionary

  • @Ryukachoo
    @Ryukachoo 2 ปีที่แล้ว

    it seems like this question has been shoved behind the leetcode paywall? not sure if its just me

  • @namanvohra8262
    @namanvohra8262 2 ปีที่แล้ว

    Thanks! Was able to come up with the recursive approach pretty quickly after learning from your clone graph video!

  • @mehmetnadi8930
    @mehmetnadi8930 ปีที่แล้ว

    I like this solution. but i also like mine :)
    class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    nodes_to_copy = {}
    def dfs(node):
    if not node:
    return None
    if node in nodes_to_copy:
    return nodes_to_copy[node]
    new = Node(node.val)
    nodes_to_copy[node] = new
    new.next = dfs(node.next)
    new.random = dfs(node.random)
    return new
    return dfs(head)

  • @anyalauria1364
    @anyalauria1364 2 ปีที่แล้ว

    brilliant as usual

  • @kaldc4958
    @kaldc4958 ปีที่แล้ว

    at 6:00 and line 17, we haven't defined old yet?

  • @Socrates225
    @Socrates225 3 ปีที่แล้ว +1

    Intended is O(1) not O(1) space complexity

  • @huansir1922
    @huansir1922 2 ปีที่แล้ว +1

    very good

  • @syafzal273
    @syafzal273 8 หลายเดือนก่อน

    Can be solved in one pass as follows -
    class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
    cloneDict = collections.defaultdict(lambda: Node(0))
    # Edge case/end of list
    cloneDict[None] = None
    curr = head
    while curr:
    clone = cloneDict[curr]
    clone.val = curr.val
    clone.next = cloneDict[curr.next]
    clone.random = cloneDict[curr.random]
    curr = curr.next
    return cloneDict[head]

  • @AmolGautam
    @AmolGautam 9 หลายเดือนก่อน

    thank you.

  • @yvanpearson7024
    @yvanpearson7024 ปีที่แล้ว

    There's a O(1) space solution, but seems to require modifying the original linked list

    • @ap84wrk
      @ap84wrk 10 หลายเดือนก่อน

      You can still do it with O(1) space and keep the original list. You need to touch it though, but you can just restore 'next' links in the 3rd pass.

  • @asder111
    @asder111 3 ปีที่แล้ว +1

    How about just one pass

  • @sanooosai
    @sanooosai 8 หลายเดือนก่อน

    great thank you

  • @sent4dc
    @sent4dc ปีที่แล้ว

    5:56 what is the 'old' there? where does it come from?

  • @ianokay
    @ianokay 5 หลายเดือนก่อน

    This makes no sense for languages which cannot store a complex object as a hashmap key. I'm really not even sure how it's serializing the object to accomplish that

  • @fraserdab
    @fraserdab 7 หลายเดือนก่อน +1

    Dude I think people found new ways to solve and the newer solution is O(1) space

  • @monicawang8447
    @monicawang8447 3 ปีที่แล้ว +1

    I have a dumb question..why we can't do "while head:" and "head = head.next" but we can set "curr = head" and loop through curr?

    • @sauravpawar5251
      @sauravpawar5251 3 ปีที่แล้ว +6

      Because head is the original pointer that we will be needing anytime in the future, so it's better not to mess with the original one and if we want to, it's better to use it's copies.
      In the end, we have used head pointer to return the final value of the function, but if we used head instead of curr, we might lose the pointer pointing at the first node of the linked list...

    • @monicawang8447
      @monicawang8447 3 ปีที่แล้ว +1

      @@sauravpawar5251 Got it, Thank you!

  • @eng_bett
    @eng_bett 3 ปีที่แล้ว +1

    2:58:00

  • @bngplays945
    @bngplays945 2 ปีที่แล้ว +1

    for the entire video I was finding old lol

  • @ap2s2000
    @ap2s2000 8 หลายเดือนก่อน

    You can do this in O(1) time without the need of the dictionary
    ```
    class Node:
    def __init__(self, val=0, next=None, random=None):
    self.val = val
    self.next = next
    self.random = random
    def copyRandomList(head):
    if not head:
    return None
    # Create copied nodes interleaved with original nodes
    curr = head
    while curr:
    new_node = Node(curr.val, curr.next, None)
    curr.next = new_node
    curr = new_node.next
    # Assign random pointers
    curr = head
    while curr:
    if curr.random:
    curr.next.random = curr.random.next
    curr = curr.next.next
    # Separate the two lists
    pseudo_head = Node(0)
    copy_curr, curr = pseudo_head, head
    while curr:
    copy_curr.next = curr.next
    curr.next = curr.next.next
    copy_curr = copy_curr.next
    curr = curr.next
    return pseudo_head.next
    ```

  • @sumkid9263
    @sumkid9263 6 วันที่ผ่านมา

    i hate this problem because brain hurty but i love this solution because its smart

  • @1oscar1984
    @1oscar1984 9 วันที่ผ่านมา

    An east medium for once!

  • @indhumathi5846
    @indhumathi5846 ปีที่แล้ว

    understood

  • @garykim313
    @garykim313 9 หลายเดือนก่อน

    Funny, I forgot to update current pointer on second pass as well.

  • @yogendrasinghvimal5043
    @yogendrasinghvimal5043 10 หลายเดือนก่อน

    This solution here is giving Time Limit Exceeded in Kotlin.

    • @yogendrasinghvimal5043
      @yogendrasinghvimal5043 10 หลายเดือนก่อน

      Here is the Code :
      fun copyRandomList(node: Node?): Node? {
      node ?: return node
      val map = hashMapOf()
      var trev: Node? = null
      var temp = node
      while(temp != null) {
      map[temp] = Node(temp.`val`)
      temp = temp?.next
      }
      temp = node
      while (temp != null) {
      trev = map[temp]
      trev?.next = map[temp?.next]
      trev?.random = map[temp?.random]
      temp = temp?.next
      }
      return map[node]
      }

  • @거너머
    @거너머 4 หลายเดือนก่อน

    damn good vid