Undefined to Null — LeetCode 2775 Python Solution
- Problem
- #2775
- Pattern
- Depth-First Search
- Reading time
- 3 min
- Source
- leetcode.com
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
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 objComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) due to recursion and rebuilt structures auxiliary |
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
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.