We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Is Object Empty

Number: 2864

Difficulty: Easy

Paid? No

Companies: Adobe


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:

  1. 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.
  2. 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.
  3. This method uses constant time checking because both length and key count operations are O(1).

Code Solutions

def isEmpty(obj):
    # Check if the object is a list (array)
    if isinstance(obj, list):
        # Return whether the list has no elements
        return len(obj) == 0
    # Check if the object is a dictionary (object)
    if isinstance(obj, dict):
        # Return whether the dictionary has no key-value pairs
        return len(obj.keys()) == 0
    # Fallback return in case the input is neither list nor dict (should not happen)
    return False

# Test cases
print(isEmpty({"x": 5, "y": 42}))  # Expected output: False
print(isEmpty({}))                # Expected output: True
print(isEmpty([None, False, 0]))   # Expected output: False
← Back to All Questions