Problem Description
Given an object or array obj (parsed from JSON), return a new “compact” object. A compact object is the same as the original except that any key holding a falsy value (where Boolean(value) returns false) is removed. This removal applies recursively to nested objects. Arrays are treated as objects whose keys are the indices.
Key Insights
- Recursively traverse each object or array.
- For each key or array element, if the value is a container (object or array), recursively compact it regardless of whether it is empty (since empty objects/arrays are considered truthy in JavaScript).
- For non-container values (numbers, booleans, strings, null), use a truthiness check (e.g. false, 0, "", null are all falsy) to decide whether to skip the value.
- Different languages treat empty arrays/objects differently; be sure to treat them as truthy as specified.
Space and Time Complexity
Time Complexity: O(n), where n is the total number of nodes (keys/elements) in the JSON structure. Space Complexity: O(n) for the recursion and the new compact data structure.
Solution
The solution uses recursion to traverse the JSON object. For each element, check if it is of type object (dictionary/hash) or array (list); if so, recursively execute the compact routine, and always include the result (even if it becomes an empty container). For primitive (non-container) values, check if they are truthy. If they are falsy (for example, 0, false, "", or null), simply omit that key or array element. This way, the new structure is a “compacted” version with all falsy primitive values removed, while preserving containers regardless of content.