MediumNo. 2775LeetCode Premium

Undefined to Null — LeetCode 2775 Python Solution

Topics
JavaScript
Reading time
3 min

The problem

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().

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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)due to recursion and rebuilt structures

Pattern: Depth-First Search

Follow one path to its end before trying the next — the default way to explore a graph. LeetCode 2775. Undefined to Null is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The depth-first search guide has the Python template for the pattern and the 366 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy
0110Balanced Binary TreeEasy

Frequently asked questions

How hard is LeetCode 2775. Undefined to Null?

LeetCode 2775. Undefined to Null is rated Medium on LeetCode.

What is the time complexity of LeetCode 2775. Undefined to Null?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2775. Undefined to Null?

The Python solution on this page uses O(n) due to recursion and rebuilt structures auxiliary space.

What topics does LeetCode 2775. Undefined to Null cover?

LeetCode 2775. Undefined to Null is tagged JavaScript on LeetCode.

Is LeetCode 2775. Undefined to Null a premium problem?

Yes. LeetCode 2775. Undefined to Null is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.