Problem Description
Given an object or an array, return if it is empty. An empty object contains no key-value pairs, and an empty array contains no elements. You may assume the object or array is the output of JSON.parse.
Key Insights
- An object is empty if it has no key-value pairs.
- An array is empty if it has no elements.
- The input is guaranteed to be a valid JSON object or array.
Space and Time Complexity
Time Complexity: O(1) for checking if the input is an object or an array. In practice, checking the size may vary but is often O(n) for large structures. Space Complexity: O(1) since we are not using any additional space that scales with the input size.
Solution
To determine if the input is empty, we can check the type of the input and then use the appropriate method to assess its emptiness. For objects, we can use Object.keys(obj).length
to count the number of keys. For arrays, we check the length
property. This approach allows us to determine if the structure is empty with minimal overhead.