LeetCode 2705: Compact Object Solution
Master LeetCode problem 2705 (Compact Object), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2705. Compact Object
Problem Explanation
Explanation:
To solve this problem, we need to recursively traverse the object or array and remove keys or indices that have falsy values. We can achieve this by iterating through the object or array and checking if the value is falsy. If it is falsy, we remove that key or index. If the value is an object or array, we recursively call the function on that value.
- Recursively traverse the object or array.
- Check if the value is falsy. If it is, remove the key or index.
- If the value is an object or array, recursively call the function on that value.
- Return the compacted object or array.
Time complexity: O(N) where N is the total number of elements in the object or array. Space complexity: O(N) for the recursive stack.
:
Solution Code
import com.google.gson.Gson;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
public class Solution {
public Object compactObject(Object obj) {
if (obj instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>) obj;
List<Object> keysToRemove = new ArrayList<>();
for (Object key : map.keySet()) {
if (!Boolean.parseBoolean(new Gson().toJson(map.get(key)))) {
keysToRemove.add(key);
} else {
map.put(key, compactObject(map.get(key)));
}
}
for (Object key : keysToRemove) {
map.remove(key);
}
} else if (obj instanceof List) {
List<Object> list = (List<Object>) obj;
List<Object> indicesToRemove = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (!Boolean.parseBoolean(new Gson().toJson(list.get(i)))) {
indicesToRemove.add(i);
} else {
list.set(i, compactObject(list.get(i)));
}
}
for (int i = indicesToRemove.size() - 1; i >= 0; i--) {
list.remove((int) indicesToRemove.get(i));
}
}
return obj;
}
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2705 (Compact Object)?
This page provides optimized solutions for LeetCode problem 2705 (Compact Object) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2705 (Compact Object)?
The time complexity for LeetCode 2705 (Compact Object) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2705 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2705 in Java, C++, or Python.