Skip to main content

Undefined to Null - Solution & Explanation

MediumPremiumFree on FleetCode3 min read
Practice this problem

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(). This function helps ensure serialized data is free of unexpected errors.

 

Example 1:

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

Example 2:

Input: obj = {"a": undefined, "b": ["a", undefined]}
Output: {"a": null,"b": ["a", null]}
Explanation: The values for obj.a and obj.b[1] have been changed from undefined to null

 

Constraints:

  • obj is a valid JSON object or array
  • 2 <= JSON.stringify(obj).length <= 105

Approach Overview

Problem Overview: You receive a JavaScript value that may contain nested objects or arrays. The task is to traverse the structure and replace every undefined value with null, while preserving the original structure and other values.

Approach 1: Recursive DFS Traversal (O(n) time, O(h) space)

The cleanest solution uses recursion to perform a depth-first traversal over the structure. Start by checking the type of the current value. If the value is exactly undefined, return null. If the value is an array, iterate through each index and recursively process each element. If the value is an object, iterate over its keys and recursively transform each property value.

The key insight is that arrays and objects are the only structures that can contain nested values requiring transformation. Primitive values like numbers, strings, and booleans can be returned directly. During traversal, every nested branch is visited exactly once, ensuring linear processing of the entire structure.

This approach naturally mirrors the hierarchical shape of JSON-like data. Each recursive call handles a smaller substructure until reaching primitives. Because recursion depth equals the nesting depth, auxiliary space depends on the maximum depth h. This pattern is closely related to techniques used in recursion and depth-first search for hierarchical data processing.

In practice, the algorithm works well for configuration objects, API responses, or parsed JSON-like structures where missing values must be normalized before serialization or storage.

Approach 2: Iterative Stack Traversal (O(n) time, O(n) space)

An iterative alternative replaces recursion with an explicit stack. Push the root value onto the stack and repeatedly process items until the stack is empty. When encountering arrays or objects, push their children onto the stack for later processing. When a value equals undefined, replace it with null.

This version performs the same logical traversal but avoids recursion depth limits. Each node is still processed once, giving O(n) time complexity. However, the stack may temporarily store many nodes, producing O(n) space usage in the worst case.

Iterative traversal is useful when the nesting depth could exceed the call stack limit or when environments discourage deep recursion.

Recommended for interviews: The recursive DFS approach is typically expected. It demonstrates clear understanding of object/array traversal and recursive decomposition. Mentioning the iterative stack alternative shows awareness of recursion limits and practical implementation trade‑offs.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Recursive DFS TraversalO(n)O(h)Best general solution for nested objects/arrays with manageable depth
Iterative Stack TraversalO(n)O(n)When recursion depth could exceed call stack limits

Video Solution

Are You Using Null And Undefined Wrong? • Web Dev Simplified • 73,519 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Undefined to Null easy or hard?
The problem is rated Medium because it requires careful handling of multiple data types and nested structures. The traversal logic is straightforward, but correctly distinguishing primitives, arrays, and objects is the key challenge.
Undefined to Null Python/Java solution
The core idea remains the same across languages: recursively traverse dictionaries/maps and lists/arrays, replacing undefined-like values with null or None. JavaScript and TypeScript implementations are most common because the problem originates from JavaScript semantics.
How to solve Undefined to Null in O(n)?
Traverse the structure using recursion or a stack. When encountering undefined, return null. If the value is an array or object, iterate through its elements or keys and recursively process each child. Since each node is visited once, the overall complexity remains O(n).
What is the best approach for Undefined to Null?
The most efficient approach is a recursive depth-first traversal of the object or array. Each value is inspected once, and undefined values are replaced with null while traversing nested structures. This solution runs in O(n) time and O(h) space, where h is the maximum nesting depth.
Is Undefined to Null asked at Google/Amazon/Meta?
Problems involving recursive traversal of nested objects or JSON-like structures appear in frontend and JavaScript-focused interviews at companies like Google, Amazon, and Meta. The question tests understanding of recursion, object iteration, and data normalization.
What data structure is used in Undefined to Null?
The solution primarily relies on recursive traversal of JavaScript objects and arrays. Conceptually it behaves like a depth-first search over a tree-like structure where each property or element acts as a node.
What is the time complexity of Undefined to Null?
The time complexity is O(n) because every element, object property, or array entry in the structure is visited exactly once during traversal. Space complexity is O(h) with recursion, where h represents the nesting depth of the structure.

Ready to solve this problem?

Practice Undefined to Null with our built-in code editor and test cases.

Practice on FleetCode