#2705

Compact Object

Medium
RecursionObject manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a single pass to build the compact object or array. We utilize recursion effectively to handle nested structures while maintaining a clean and efficient traversal.

⚙️

Algorithm

6 steps
  1. 1Step 1: Create a function that takes the input object or array.
  2. 2Step 2: Initialize an empty result object or array.
  3. 3Step 3: Iterate through each key-value pair in the object or each element in the array.
  4. 4Step 4: For each value, check if it is falsy. If it is not, add it to the result.
  5. 5Step 5: If the value is an object or array, recursively call the function on it.
  6. 6Step 6: Return the result object or array.
solution.py7 lines
1def compact(obj):
2    if isinstance(obj, dict):
3        return {k: compact(v) for k, v in obj.items() if v}
4    elif isinstance(obj, list):
5        return [compact(v) for v in obj if v]
6    return obj
7

Complexity note: This complexity is due to the need to store the results in a new object or array, where n is the total number of elements in the input.

  • 1Understanding how to handle nested structures is crucial for this problem.
  • 2Recognizing the difference between truthy and falsy values helps in filtering the data correctly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.