
Sponsored
Sponsored
This approach leverages a recursive depth-first search to traverse the object or array. We remove any keys or indices associated with falsy values during traversal. The recursion ensures nested structures are appropriately compacted.
The time complexity is O(n), where n is the total number of elements (including nested) in the object. The space complexity also depends on the depth of recursion, primarily O(d) where d is the depth of nested objects.
1using System.Collections;
using System.Collections.Generic;
public class CompactObject
{
public static object Compact(object obj)
{
if (obj is IList list)
{
var result = new List<object>();
foreach (var item in list)
{
if (item != null && !Equals(item, false))
{
var compactedItem = Compact(item);
if (compactedItem != null)
{
result.Add(compactedItem);
}
}
}
return result;
}
if (obj is IDictionary dictionary)
{
var result = new Dictionary<string, object>();
foreach (DictionaryEntry entry in dictionary)
{
if (entry.Value != null && !Equals(entry.Value, false))
{
var compactedValue = Compact(entry.Value);
if (compactedValue != null)
{
result.Add((string)entry.Key, compactedValue);
}
}
}
return result;
}
return obj;
}
public static void Main(string[] args)
{
var obj = new Dictionary<string, object>
{
{ "a", null },
{ "b", new List<object>{ false, 1 } }
};
Console.WriteLine(Compact(obj));
}
}This C# solution handles JSON-like structures using easy recursion while identifying and excluding falsy elements. Dictionaries and Lists in C# play roles similar to objects and arrays in JavaScript, aiding in traversal.
Instead of recursion, this approach uses an iterative depth-first search pattern using a stack to manage the traversal. It ensures that nested structures are compacted by maintaining traversal state without deep recursion, mitigating possible stack overflows in languages with limited recursion depth control.
Time Complexity: O(n) as each element is processed once; Space Complexity: O(n) where n encapsulates all elements since the entire structure can potentially end up in the stack.
1function compactIterative(obj) {
2 const stack = [{ obj, parent: null, key: null }];
3
4 while (stack.length) {
5 const { obj: current, parent, key } = stack.pop();
6
7 if (Array.isArray(current)) {
8 for (let i = current.length - 1; i >= 0; i--) {
9 if (!current[i]) current.splice(i, 1);
10 else stack.push({ obj: current[i], parent: current, key: i });
11 }
12 } else if (current !== null && typeof current === 'object') {
13 Object.keys(current).forEach(k => {
14 if (!current[k]) delete current[k];
15 else stack.push({ obj: current[k], parent: current, key: k });
16 });
17 }
18 }
19
20 return obj;
21}
22
23// Example usage
24console.log(compactIterative({ a: null, b: [false, 1] }));This JavaScript code uses an iterative approach with a stack to track objects or arrays needing traversal. It efficiently removes keys or elements with falsy values, addressing deeply nested structures without recursion.