We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Compact Object

Number: 2804

Difficulty: Medium

Paid? No

Companies: N/A


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.


Code Solutions

# Python solution with line-by-line comments
def compact(obj):
    # If obj is a dictionary, process each key-value pair
    if isinstance(obj, dict):
        new_obj = {}
        for key, value in obj.items():
            # If the value is a dict or list, process it recursively
            if isinstance(value, dict) or isinstance(value, list):
                new_val = compact(value)
                # Always include container objects (even if empty)
                new_obj[key] = new_val
            else:
                # For primitive types, only include if truthy
                if value:
                    new_obj[key] = value
        return new_obj
    # If obj is a list, process each element
    elif isinstance(obj, list):
        new_arr = []
        for element in obj:
            # Recursively process containers
            if isinstance(element, dict) or isinstance(element, list):
                new_arr.append(compact(element))
            else:
                # For primitives, include only if truthy
                if element:
                    new_arr.append(element)
        return new_arr
    else:
        # If not a container, return the value as is
        return obj

# Example usage:
# print(compact([None, 0, 5, [0], [False, 16]]))
← Back to All Questions