00:00

Problem Statement

Input/Output Examples

Visual Explanation

An object is only immutable if nothing outside it can reach its mutable parts. Copying mutable inputs and returning unmodifiable views closes both doors.

Approaches

Both approaches produce the same immutable invoice. The first spells out every rule; the second lets a record do most of the work.

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 k is the number of items. Creating an invoice copies the list once; reading it never copies anything because the stored list is already unmodifiable.

Interview Tips and Recommended Approach

  • Recite the rules: final class, private final fields, no setters, defensive copies in and out.
  • Remember mutable fields. final List only fixes the reference; the list itself can still change.
  • Know that records are shallowly immutable. A record holding a mutable list still needs a copy.
  • Explain the benefits: thread safety without locks, safe map keys and simpler reasoning.

Recommended Approach: Final Class With Defensive Copies

Why: it shows every rule explicitly, which is what interviewers want to hear. In new code, a record with a compact constructor is the shorter way to get the same result.