惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
S
SegmentFault 最新的问题
N
Netflix TechBlog - Medium
B
Blog
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 聂微东
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
大猫的无限游戏
大猫的无限游戏
U
Unit 42
J
Java Code Geeks
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
腾讯CDC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Copy List with Random Pointer
Jaspreet singh · 2026-06-14 · via DEV Community

Jaspreet singh

This problem is a classic Linked List interview question that tests your understanding of deep copying and pointer manipulation.

The challenge is not copying the next pointers, but correctly maintaining the relationships created by the random pointers.


Problem Statement

Given a linked list where each node contains:

int val;
Node next;
Node random;

Create a deep copy of the list.

The copied list should:

  • Contain completely new nodes.
  • Preserve the next relationships.
  • Preserve the random relationships.
  • Not reference any node from the original list.

Brute Force Intuition

For every original node:

  • Create a copy node.
  • Store mapping:
Original Node -> Copied Node

using a HashMap.

After creating all nodes:

  • Traverse again.
  • Connect next pointers.
  • Connect random pointers using the map.

Interview Explanation

Since random pointers can point anywhere in the list, we first create a clone of every node and store the original-to-copy mapping in a HashMap. During a second traversal, we use this mapping to connect both next and random pointers correctly.

Complexity

Time  : O(n)

Space : O(n)


Moving Towards the Optimal Solution

Can we avoid the HashMap?

Notice:

Original:
A -> B -> C

What if we insert cloned nodes in between?

A -> A' -> B -> B' -> C -> C'

Now every clone sits immediately after its original node.

This creates a shortcut that allows us to assign random pointers without a HashMap.


Key Observation

Suppose:

A.random = C

After inserting clones:

A -> A' -> B -> B' -> C -> C'

Then:

A'.random = C'

And:

C' = A.random.next

Therefore:

copy.random = original.random.next;

This is the entire trick behind the optimal solution.


Optimal Approach

Step 1

Insert cloned nodes between originals.

A -> A' -> B -> B' -> C -> C'

Step 2

Assign random pointers.

copy.random = original.random.next;

Step 3

Separate both lists.

Original:

A -> B -> C

Copied:

A' -> B' -> C'


Dry Run

Original List

1 -> 2 -> 3

1.random -> 3
2.random -> 1
3.random -> 2


After Inserting Copies

1 -> 1' -> 2 -> 2' -> 3 -> 3'


Setting Random Pointers

1'.random = 3'
2'.random = 1'
3'.random = 2'

using:

cur.next.random = cur.random.next;


Separate Lists

Original:

1 -> 2 -> 3

Copied:

1' -> 2' -> 3'

Deep copy created successfully.


Optimal Java Solution

class Solution {

    public Node copyRandomList(Node head) {

        if (head == null)
            return null;

        // Step 1: Insert copied nodes
        Node cur = head;

        while (cur != null) {

            Node copy = new Node(cur.val);

            copy.next = cur.next;
            cur.next = copy;

            cur = copy.next;
        }

        // Step 2: Set random pointers
        cur = head;

        while (cur != null) {

            if (cur.random != null) {
                cur.next.random = cur.random.next;
            }

            cur = cur.next.next;
        }

        // Step 3: Separate original and copied list
        Node dummy = new Node(0);
        Node copyTail = dummy;

        cur = head;

        while (cur != null) {

            Node copy = cur.next;

            cur.next = copy.next;

            copyTail.next = copy;
            copyTail = copy;

            cur = cur.next;
        }

        return dummy.next;
    }
}


Why This Works

By inserting each copied node immediately after its original node:

Original -> Copy

we can access the copied version of any node in O(1) time using:

original.next

This removes the need for a HashMap entirely.


Complexity Analysis

Time  : O(n)

Space : O(1)

No extra HashMap is used.


Pattern Recognition

Whenever you see:

  • Clone Linked List
  • Random Pointer
  • Deep Copy Structure

Think:

Interweave Copies
→ Set Random Pointers
→ Separate Lists

This is the standard optimal interview pattern.


Interview One-Liner

Instead of using a HashMap, I interleave cloned nodes with original nodes, use the adjacency relationship to assign random pointers in O(1), and finally separate the two lists, achieving O(n) time and O(1) extra space.