Explorer
JavaScript

Write a function `deepFreeze(obj)` that deeply freezes an object so all nested properties are also immutable.

Problem Statement

<p>Write a function <code>deepFreeze(obj)</code> that deeply freezes an object so all nested properties are also immutable.</p>

Examples

Input: const obj = deepFreeze({ a: { b: 1 } }); obj.a.b = 2;

Output: obj.a.b remains 1

Explanation: All nested levels are frozen.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Object.freeze() only freezes top-level properties. šŸ’” Hint 2: Recursively freeze all object-type properties. šŸ’” Hint 3: Object.freeze(obj); Object.values(obj).forEach(val => { if (typeof val === "object" && val !== null) deepFreeze(val); });

Editorial & Approach

Problem Overview & Intuition

To solve Object.freeze Deep, we consider the execution characteristics of JavaScript engines. Write a function `deepFreeze(obj)` that deeply freezes an object so all nested properties are also immutable. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (object.freeze() only freezes top-level properties).
  3. Implement Logic: Handle state and transformations efficiently (recursively freeze all object-type properties).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function deepFreeze(obj) {
  Object.freeze(obj);
  Object.values(obj).forEach(val => {
    if (typeof val === "object" && val !== null && !Object.isFrozen(val)) {
      deepFreeze(val);
    }
  });
  return obj;
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Object.freeze Deep

Medium

Write a function deepFreeze(obj) that deeply freezes an object so all nested properties are also immutable.

Example Scenarios
1Example 1
Input: const obj = deepFreeze({ a: { b: 1 } }); obj.a.b = 2;
Output: obj.a.b remains 1
Explanation:

All nested levels are frozen.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[1,2]