Problem

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.

Examples

Example 1

1
2
3
Input: obj = {"x": 5, "y": 42}
Output: false
Explanation: The object has 2 key-value pairs so it is not empty.

Example 2

1
2
3
Input: obj = {}
Output: true
Explanation: The object doesn't have any key-value pairs so it is empty.

Example 3

1
2
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 array
  • 2 <= JSON.stringify(obj).length <= 10^5

Can you solve it in O(1) time?

Solution

Method 1 – Type and Length Check

Intuition

To check if an object or array is empty, we can use Object.keys for objects and check the length property for arrays. Both are outputs of JSON.parse, so we don’t need to handle other types.

Approach

  1. If the input is an array, return true if its length is 0.
  2. If the input is an object, return true if it has no own enumerable properties.
  3. Otherwise, return false.

Code

1
2
3
4
function isEmpty(obj) {
  if (Array.isArray(obj)) return obj.length === 0;
  return Object.keys(obj).length === 0;
}
1
2
3
4
function isEmpty(obj: any): boolean {
  if (Array.isArray(obj)) return obj.length === 0;
  return Object.keys(obj).length === 0;
}

Complexity

  • ⏰ Time complexity: O(n) — n is the number of keys for objects or elements for arrays (for Object.keys or length).
  • 🧺 Space complexity: O(n) — For the array returned by Object.keys (for objects).