Given an object or an array, return if it is empty.
You may assume the object or array is the output of JSON.parse.
Example 1:
Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.
Example 2:
Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.
Example 3:
Input: obj = [null, false, 0] Output: false Explanation: The array has 3 elements so it is not empty.
Constraints:
obj is a valid JSON object or array2 <= JSON.stringify(obj).length <= 105Can you solve it in O(1) time?
This approach involves using language-specific properties or methods that can quickly determine if an object or array has any elements. For objects, this often involves checking the number of keys, while for arrays it's about checking the length.
In this hypothetical C solution, we are assuming the use of some JSON library where JSON objects and arrays have defined length and size. The isObjectEmpty function checks if the length (or size) is zero to determine emptiness.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1) because we are directly accessing built-in properties.
Space Complexity: O(1) since no extra space is used except for few variables.
This method relies on the use of iterators to quickly assess emptiness by attempting to iterate over the first element. If there is no element to begin with, it returns empty.
This is a more experimental C solution assuming some JSON library where iterators can be compared to check for zero elements (i.e., iterators at the beginning equal iterators at the end).
C++
Java
Python
C#
JavaScript
Time Complexity: O(1).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Using Size/Length Properties | Time Complexity: O(1) because we are directly accessing built-in properties. |
| Using Iterator Method | Time Complexity: O(1). |
I solved too many Leetcode problems • NeetCodeIO • 101,495 views views
Watch 9 more video solutions →Practice Is Object Empty with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor