
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.
1def compact_iterative(obj):
2 stack = [(obj, None, None)] # (current_obj, parent, key/index)
3 while stack:
4 current, parent, key = stack.pop()
5 if isinstance(current, dict):
6 for k in list(current.keys()):
7 if not current[k]:
8 del current[k]
9 else:
10 stack.append((current[k], current, k))
11 elif isinstance(current, list):
12 for idx in range(len(current) - 1, -1, -1):
13 if not current[idx]:
14 current.pop(idx)
15 else:
16 stack.append((current[idx], current, idx))
17
18 return obj
19
20# Example Usage
21example_dict = {"a": None, "b": [False, 1]}
22print(compact_iterative(example_dict))This Python implementation uses an explicit stack to perform an iterative deep-first traversal on the JSON structure. By handling keys/indices dynamically, the solution effectively compacts nested constructs without recursive function calls.