00:00

Problem Statement

Input/Output Examples

Visual Explanation

Only mutable inner objects need copying. Immutable ones, such as String, can be shared safely because no one can change them.

Approaches

Both approaches create a deep copy. The first uses a copy constructor; the second overrides clone().

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the number of members. A deep copy copies every reference in the list once; the member strings themselves are shared because they are immutable.

Interview Tips and Recommended Approach

  • Define both terms. Shallow copies the fields; deep copies the objects the fields point to.
  • Copy only what can change. Immutable objects never need a deep copy.
  • Prefer copy constructors or factory methods to clone().
  • Go as deep as needed. A list of mutable objects needs each element copied too.

Recommended Approach: Copy Constructor

Why: it is explicit, needs no special interface and makes the copied fields visible in one place.