Is Object Empty Problem
#2727
Description
LeetCode Problem 2727.
Given an object or an array, return if it is empty.
- An empty object contains no key-value pairs.
- An empty array contains no elements.
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:
objis a valid JSON object or array2 <= JSON.stringify(obj).length <= 10^5
Can you solve it in O(1) time?
Solution
Approach: Stop at the first key
An object or array is empty exactly when iterating over it yields nothing. A for...in loop that returns false on its first iteration answers the question after looking at one key at most, so it runs in constant time. Object.keys(obj).length === 0 is shorter but builds the whole key list first, which is linear.
Because the input comes from JSON.parse, it has no inherited enumerable properties, so for...in is safe here.
Complexity: Time O(1), space O(1).
/**
* @param {Object|Array} obj
* @return {boolean}
*/
var isEmpty = function (obj) {
for (const key in obj) {
return false;
}
return true;
};