LeetCode Problem Workspace
Compact Object
Compact Object requires removing all falsy values from an object or array recursively to produce a clean, minimal structure efficiently.
0
Topics
2
Code langs
0
Related
Practice Focus
Medium · Compact Object core interview pattern
Answer-first summary
Compact Object requires removing all falsy values from an object or array recursively to produce a clean, minimal structure efficiently.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Compact Object core interview pattern
To solve Compact Object, recursively iterate through each key or index, removing entries where Boolean(value) is false. Nested objects and arrays must also be processed to ensure all falsy values are eliminated. This approach guarantees a minimal, compact structure while preserving the original data hierarchy and handles arrays as objects with numerical keys.
Problem Statement
Given an object or array obj, return a new version where all keys or indices containing falsy values are removed. Arrays are treated as objects with numeric keys, and falsy values include false, null, 0, '', undefined, and NaN. Nested objects and arrays must also be compacted recursively.
The input obj is guaranteed to be valid JSON and can be parsed directly. The result should maintain the original structure but omit any falsy values at any depth, producing a compacted object or array that preserves all truthy data only.
Examples
Example 1
Input: obj = [null, 0, false, 1]
Output: [1]
All falsy values have been removed from the array.
Example 2
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
obj["a"] and obj["b"][0] had falsy values and were removed.
Example 3
Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]
obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints
- obj is a valid JSON object
- 2 <= JSON.stringify(obj).length <= 106
Solution Approach
Recursive Filtering
Traverse obj recursively, checking each value. If the value is an object or array, call the same function recursively. Keep only keys or indices where the value is truthy after processing nested elements.
Array as Object Handling
Treat arrays like objects with numeric keys, allowing the same recursive filtering logic. After filtering, reconstruct the array from remaining truthy indices to preserve order and remove gaps.
Return Compacted Structure
After recursion completes, return the modified object or array with all falsy values removed. Ensure nested arrays and objects are also compacted, producing a fully minimal structure for accurate output.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(N) |
| Space | O(N) |
Time complexity is O(N) since each element is visited once. Space complexity is O(N) due to recursion and constructing the new compacted structure, proportional to the number of truthy elements.
What Interviewers Usually Probe
- Expect recursive traversal or iterative stack solutions for nested objects.
- Look for handling arrays as objects to ensure correct index compaction.
- Watch for correct identification of all falsy values, including 0 and empty strings.
Common Pitfalls or Variants
Common pitfalls
- Failing to recurse into nested arrays or objects and leaving falsy values.
- Removing array elements incorrectly, breaking the original order.
- Misidentifying truthy and falsy values, leading to incorrect output.
Follow-up variants
- Compact only top-level keys without recursion for a simpler version.
- Compact objects but keep arrays intact, testing selective recursion.
- Compact and also sort keys or array elements after filtering for deterministic output.
FAQ
What is a falsy value in the Compact Object problem?
Falsy values include false, null, 0, '', undefined, and NaN, which must be removed from all objects or arrays recursively.
Does Compact Object require recursion for nested arrays?
Yes, nested arrays and objects must be processed recursively to remove all falsy values at any depth.
How are arrays treated in the Compact Object problem?
Arrays are treated as objects with numeric keys so that filtering logic can apply uniformly across objects and arrays.
Can GhostInterview handle very large JSON objects for Compact Object?
Yes, GhostInterview optimizes recursion and memory use to efficiently process large objects within the given constraints.
What is the primary interview pattern tested by Compact Object?
The problem tests the Compact Object core interview pattern, focusing on recursive filtering and handling nested structures correctly.
Solution
Solution 1: Recursion
If `obj` is not an object or is null, the function will return it as is, because there's no need to check for keys in non-object values.
/**
* @param {Object|Array} obj
* @return {Object|Array}
*/
var compactObject = function (obj) {
if (!obj || typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.filter(Boolean).map(compactObject);
}
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value) {
acc[key] = compactObject(value);
}
return acc;
}, {});
};