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

Difficulty: Easy


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.


Code Solutions

def is_empty(obj):
    if isinstance(obj, dict):  # Check if the input is a dictionary
        return len(obj) == 0   # Return True if it has no key-value pairs
    elif isinstance(obj, list):  # Check if the input is a list
        return len(obj) == 0     # Return True if it has no elements
    return False  # For other types, return False as they are neither dict nor list
← Back to All Questions