Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2775: Undefined to Null

In this guide, we solve Leetcode #2775 Undefined to Null in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a deeply nested object or array obj, return the object obj with any undefined values replaced by null. undefined values are handled differently than null values when objects are converted to a JSON string using JSON.stringify().

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: JavaScript

Intuition

We need to traverse every value in a potentially nested structure and replace only the undefined values.

A depth-first walk mirrors the structure naturally, letting us rebuild lists and dictionaries while keeping other values intact.

Approach

Recursively walk the input.

When we encounter the JavaScript-style undefined, replace it with None (Python's null). For lists and dictionaries, rebuild them by applying the same conversion to each child.

Steps:

  • If the value is undefined, return None.
  • If it's a list, map the conversion over all elements.
  • If it's a dict, convert every value.
  • Otherwise, return the value unchanged.

Example

Input: obj = {"a": undefined, "b": 3} Output: {"a": null, "b": 3} Explanation: The value for obj.a has been changed from undefined to null

Python Solution

class Undefined: pass UNDEFINED = Undefined() class Solution: def undefinedToNull(self, obj): if obj is UNDEFINED: return None if isinstance(obj, list): return [self.undefinedToNull(x) for x in obj] if isinstance(obj, dict): return {k: self.undefinedToNull(v) for k, v in obj.items()} return obj

Complexity

The time complexity is O(n)O(n)O(n), and the space complexity is O(n)O(n)O(n) due to recursion and rebuilt structures.

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy