Problem Description
Given an object or an array, determine whether it is empty. An empty object has no key-value pairs, and an empty array has no elements.
Key Insights
- For arrays, check if the length (or size) is zero.
- For objects, check if the count of keys is zero.
- The input is the result of JSON.parse, so it is guaranteed to be a valid object or array.
- The solution can be achieved in O(1) time using built-in properties.
Space and Time Complexity
Time Complexity: O(1) Space Complexity: O(1)
Solution
The approach is straightforward:
- Determine if the input is an array:
- In languages like JavaScript and Python, use the built-in methods (Array.isArray or isinstance) to verify if the input is an array and then check its length.
- If it is not an array, treat it as an object:
- Retrieve the list of keys (using Object.keys in JavaScript or dict.keys in Python) and check if that list is empty.
- This method uses constant time checking because both length and key count operations are O(1).