#2727
Is Object Empty
EasyHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the built-in methods to check for emptiness directly, which is efficient and clear. We can handle both objects and arrays in a single function call.
⚙️
Algorithm
3 steps- 1Step 1: Check if the input is an array using Array.isArray().
- 2Step 2: If it's an array, return its length check.
- 3Step 3: If it's an object, return the result of Object.keys() length check.
solution.py2 lines
1def is_empty(obj):
2 return (isinstance(obj, list) and len(obj) == 0) or (isinstance(obj, dict) and len(obj) == 0)ℹ
Complexity note: The optimal solution has a time complexity of O(n) because we still need to check the length of the keys or elements, but it is more concise and clear.
- 1Understanding the difference between objects and arrays is crucial for checking emptiness.
- 2Using built-in functions like Object.keys() and Array.isArray() simplifies the code.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.