2705. Compact Object LeetCode Solution
In this guide, you will get 2705. Compact Object LeetCode Solution with the best time and space complexity. The solution to Compact Object problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Compact Object solution in C++
- Compact Object solution in Java
- Compact Object solution in Python
- Additional Resources

Problem Statement of Compact Object
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 object
2 <= JSON.stringify(obj).length <= 106
Complexity Analysis
- Time Complexity: Google AdSense
- Space Complexity: Google Analytics
2705. Compact Object LeetCode Solution in C++
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;
function compactObject(obj: Obj): Obj {
return dfs(obj) as Obj;
}
function dfs(value: JSONValue): JSONValue {
if (value === null) {
return null;
}
if (Array.isArray(value)) {
return value.filter(Boolean).map(dfs);
}
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (Boolean(value[key])) {
value[key] = dfs(value[key]);
} else {
delete value[key];
}
}
}
return value;
}
/* code provided by PROGIEZ */
2705. Compact Object LeetCode Solution in Java
N/A
// code provided by PROGIEZ
2705. Compact Object LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.