
Sponsored
Sponsored
This approach leverages a recursive depth-first search to traverse the object or array. We remove any keys or indices associated with falsy values during traversal. The recursion ensures nested structures are appropriately compacted.
The time complexity is O(n), where n is the total number of elements (including nested) in the object. The space complexity also depends on the depth of recursion, primarily O(d) where d is the depth of nested objects.
1
Python makes handling this problem quite intuitive with its dynamic typing and list/dict comprehensions. The code above recursively filters out elements or keys/values that evaluate to 'False', effectively compacting the structure.
Instead of recursion, this approach uses an iterative depth-first search pattern using a stack to manage the traversal. It ensures that nested structures are compacted by maintaining traversal state without deep recursion, mitigating possible stack overflows in languages with limited recursion depth control.
Time Complexity: O(n) as each element is processed once; Space Complexity: O(n) where n encapsulates all elements since the entire structure can potentially end up in the stack.
1function compactIterative(obj) {
2 const stack = [{ obj, parent: null, key: null }];
3
4 while (stack.length) {
5 const { obj: current, parent, key } = stack.pop();
6
7 if (Array.isArray(current)) {
8 for (let i = current.length - 1; i >= 0; i--) {
9 if (!current[i]) current.splice(i, 1);
10 else stack.push({ obj: current[i], parent: current, key: i });
11 }
12 } else if (current !== null && typeof current === 'object') {
13 Object.keys(current).forEach(k => {
14 if (!current[k]) delete current[k];
15 else stack.push({ obj: current[k], parent: current, key: k });
16 });
17 }
18 }
19
20 return obj;
21}
22
23// Example usage
24console.log(compactIterative({ a: null, b: [false, 1] }));This JavaScript code uses an iterative approach with a stack to track objects or arrays needing traversal. It efficiently removes keys or elements with falsy values, addressing deeply nested structures without recursion.