Given an object or array obj, return a compact object.
A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false.
You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.
Example 1:
Input: obj = [null, 0, false, 1] Output: [1] Explanation: All falsy values have been removed from the array.
Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: 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]] Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints:
obj is a valid JSON object2 <= JSON.stringify(obj).length <= 106When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute-force approach to compacting an object involves exhaustively exploring all possible object structures. We achieve this by recursively examining each element within the object and deciding whether to include it or exclude it. This generates every possible compacted object variation, and we then select the desired result.
Here's how the algorithm would work step-by-step:
def compact_object(input_object):
# Helper function to determine if a value is falsey
def is_falsey(value):
return value is None or value is False
# This function recursively compacts the object
def compact_recursive(current_object):
if isinstance(current_object, dict):
compacted_object = {}
for key, value in current_object.items():
compacted_value = compact_recursive(value)
# Only include values that aren't falsey
if not is_falsey(compacted_value):
compacted_object[key] = compacted_value
return compacted_object
elif isinstance(current_object, list):
# Filter out falsey values from lists
compacted_list = [compact_recursive(item) for item in current_object if not is_falsey(item)]
return compacted_list
else:
# Base case: return the value if not a dict or list
return current_object
# Start the recursive compaction process
return compact_recursive(input_object)The challenge is to create a new object that contains only the truthy values from the original object. We will essentially be filtering the original object, keeping only what we want.
Here's how the algorithm would work step-by-step:
def compact_object(input_object):
if input_object is None:
return None
if isinstance(input_object, dict):
# Create a new dictionary to store the compacted object.
compacted_object = {}
for key, value in input_object.items():
compacted_value = compact_object(value)
if compacted_value:
compacted_object[key] = compacted_value
return compacted_object
if isinstance(input_object, list):
# Create a new list to store the compacted array.
compacted_array = []
for item in input_object:
compacted_item = compact_object(item)
# Only append items that are not nullish.
if compacted_item:
compacted_array.append(compacted_item)
return compacted_array
# Return non-nullish primitive values as is.
return input_object if input_object else None| Case | How to Handle |
|---|---|
| Null or undefined input object | Return an empty object if the input is null or undefined to prevent errors. |
| Empty object as input | Return an empty object immediately since there is nothing to compact. |
| Input object with only null or undefined values at the top level | Return an empty object because after removal of null/undefined, the result is empty. |
| Nested objects and arrays with a mix of valid and invalid values | Recursively process each level to remove null, undefined, empty arrays and objects appropriately. |
| Deeply nested objects and arrays causing potential stack overflow | While Javascript has recursion limits, the object structure should generally not be so deeply nested as to cause stack overflow for typical interview problems; however iterative approach avoids stackoverflow issue entirely. |
| Object containing circular references | Circular references could lead to infinite loops; use a Set to keep track of visited objects and arrays to prevent infinite recursion. |
| An array containing only null/undefined values | Should compact down to an empty array which is then removed if it's the value of a key in the parent object. |
| Object with number as key and null/undefined value | Should compact as with other cases - remove key-value pair where value is null/undefined. |