Taro Logo

Is Object Empty

Easy
Asked by:
Profile picture
Profile picture
Profile picture
22 views

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:

  • obj is a valid JSON object or array
  • 2 <= JSON.stringify(obj).length <= 105
Can you solve it in O(1) time?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What data types can the values of the object's properties be?
  2. Can the input object be null or undefined?
  3. Should I only consider own properties (i.e., properties directly defined on the object), or should I also consider inherited properties from its prototype chain?
  4. What should be returned if the input is not an object (e.g., a number, string, or array)? Should I throw an error, or return a boolean indicating emptiness?
  5. By 'empty,' do you mean the object has no enumerable properties, or are non-enumerable properties also considered?

Brute Force Solution

Approach

The brute force way to check if an object is empty involves examining every single part of the object to see if it contains anything. We're going to manually check each part until we find something, or until we've checked everything and found nothing.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first thing inside the object.
  2. If that first thing exists, the object is not empty, and we're done.
  3. If the first thing doesn't exist, move on to the second thing inside the object.
  4. Check if the second thing exists. If it does, the object is not empty, and we're done.
  5. Keep going through each thing inside the object, one by one.
  6. If you get to the end of the object and haven't found anything that exists, then the object is empty.

Code Implementation

def is_object_empty_brute_force(input_object):
    # Iterate through all keys in the object
    for key in input_object:

        # If any key exists, the object is not empty
        return False

    # If no keys were found, the object is empty
    return True

Big(O) Analysis

Time Complexity
O(n)The described approach iterates through each 'thing' inside the object until it finds a non-empty element or reaches the end. In the worst case, the object is either empty or the last element checked is the only non-empty one, requiring us to iterate through all n elements, where n is the number of properties in the object. Therefore, the time complexity is directly proportional to the number of properties, resulting in O(n) time complexity.
Space Complexity
O(1)The algorithm described iterates through the elements of the object one by one, checking for existence. It doesn't explicitly create any additional data structures like arrays, lists, or hash maps to store intermediate results or track visited elements. Therefore, only a constant amount of extra memory is used, potentially for loop counters or temporary variables, irrespective of the size of the object (N). The auxiliary space remains constant, hence O(1).

Optimal Solution

Approach

The best way to determine if an object is empty is to check if it has any properties at all. We want to avoid looking at specific properties, as that would be inefficient. The fastest approach checks for the existence of any property, and returns right away if it finds one.

Here's how the algorithm would work step-by-step:

  1. First, try to get the first property of the object. This is a quick way to see if the object has anything in it.
  2. If you can successfully get a property, it means the object is not empty, so you can say 'no, it's not empty' and stop right away.
  3. If you can't get a property (because there aren't any), it means the object is empty, so you can say 'yes, it's empty'.

Code Implementation

def is_object_empty(input_object):
    # Attempt to retrieve the first key to check for emptiness
    try:
        first_key = next(iter(input_object))

        # If the object has at least one key, it's not empty
        return False

    except StopIteration:
        # If there are no keys, the object is empty
        return True

Big(O) Analysis

Time Complexity
O(1)The algorithm attempts to retrieve the first property of the object. In the best case, if the object is not empty, the algorithm finds a property immediately and returns. In the worst case, if the object is empty, it iterates until the end of the object's properties which is still considered a fixed cost. Because the cost does not depend on the size of the input object (n), but on finding the *first* property or determining there isn't one, the time complexity is constant.
Space Complexity
O(1)The algorithm checks for the existence of a property in the object. It doesn't create any new data structures or auxiliary storage that scales with the size of the input object. The operation is performed in-place without allocating additional memory proportional to the number of properties in the object, N. Thus, the auxiliary space complexity is constant.

Edge Cases

Null or undefined object input
How to Handle:
Return true immediately as null/undefined objects are considered empty
Object with inherited properties only
How to Handle:
Use hasOwnProperty() to ensure only own properties are considered.
Object with a very large number of properties
How to Handle:
The solution iterates over properties, and should perform reasonably well even with a large number of them although very large objects could lead to performance degradation, but it will still provide a valid result
Object with symbolic properties
How to Handle:
The `for...in` loop (when combined with `hasOwnProperty()`) and `Object.keys()` do not enumerate Symbol properties; ensure testing includes these if the requirement includes symbols
Object with properties that have getter/setter methods
How to Handle:
Accessing a getter should not throw an error or have unintended side effects within the emptiness check.
Frozen object
How to Handle:
The solution should not attempt to modify the object; therefore freezing will not impact the solution.
Object created with Object.create(null)
How to Handle:
Object.create(null) creates an object without a prototype, so it should not cause issues if combined with `hasOwnProperty()` to avoid checking inherited properties.
Empty object {} passed as input
How to Handle:
Return true since it has no properties