Welcome to my personal website. I use this space to share some of my thoughts and software that I write in my free time. Sometimes I also publish photos. If you want to get in touch please use LinkedIn or Mastodon.
Given a head of a list with pointers to next and a random element, copy the list to a new list without any random pointers pointing to the old list.
One way to solve this is to copy first all the nodes into a new list via the next links. Next, we create two pointers, one pointing at the original list and the other one pointing at the new list. We then iterate over the original list (while moving the second pointer as well) and check at each step if we hit our current node in the original list via random. If we do, we make a connection in the new list as well. One specialty is that two random pointers can point at the same element. For this reason, we cannot simply stop once we found the first pointer but have to continue until the end.
This solution has to iterate multiple times over the same list as we start from the destination and not from the source. For a more efficient solution, see the altnerative solution below.
Runtime: 106 ms, faster than 5.23% of Python3 online submissions for Copy List with Random Pointer. Memory Usage: 15 MB, less than 46.50% of Python3 online submissions for Copy List with Random Pointer.
Alternate Solution
Another solution is to first interweave the new nodes with the old nodes such that after each original node, there’s a copy of the original node, pointing to the next node, and so on. When following for every node the random path, we just can set the next.random to random.next as the copy of the node comes always after the original node. This allows for a time complexity of O(3n).
About the author
Friedrich Ewald is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.