Is Object Empty solution and explanation
5 more videos on this problem
Is Object Empty | Leetcode 2727 | JSON | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 9:48 · 1K views
is object empty - leetcode 2727Swagasoft Programming · 7:08 · 553 views
#day20 | 2727. Is Object Empty | 30 Days of JavaScript | Leetcode-2727 | What is JSON?| Object in JSCoding with Ankita · 13:22 · 435 views
Mastering O(1) Complexity: Check If an Object or Array is Empty in JavaScript | 2727vanAmsen · 3:19 · 190 views
2727. Is Object EmptyTech Guides · 2:05 · 63 views
#2727 Is Object Empty #object |30 Days of JavaScript |Programmers Choice #javascript #leetcode #jsProgrammers choice · 5:16 · 43 views
The 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.
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 <= 105
Approach overview
Problem Overview: You receive an object or array and need to determine whether it contains any elements. Return true if it has no enumerable keys or items, otherwise return false.
Approach 1: Using Size/Length Properties (O(n) time, O(1) space)
The most common solution checks how many keys exist in the object. In JavaScript this typically means calling Object.keys(obj) and inspecting the resulting array length. If the length is 0, the object has no properties. Arrays follow the same idea using their length field. The algorithm internally iterates through the object's enumerable keys, giving a time complexity of O(n) where n is the number of properties, while using constant auxiliary space aside from the key list created by the runtime.
This approach is concise and readable, which is why it appears frequently in production code and interviews. It relies on built-in language helpers that already implement efficient iteration over object properties.
Approach 2: Using Iterator Method (O(n) time, O(1) space)
Another approach directly iterates through the object using a loop such as for...in (JavaScript) or language-specific iterators in C++, Java, or Python. The key idea is early termination: the moment you encounter the first property, you know the object is not empty and can immediately return false. If the loop finishes without visiting any property, the object is empty.
This method avoids creating an intermediate list of keys and may exit earlier in practice if the object contains elements. The worst-case complexity is still O(n) because every key might need to be checked. The space complexity remains O(1) since no additional data structures are required. The technique relies on fundamental data structure traversal patterns and is useful when working close to the runtime or when minimizing allocations.
Recommended for interviews: Both solutions are acceptable. The size/length property approach is the most recognizable and communicates the intent immediately, so many interviewers expect it first. The iterator-based approach demonstrates deeper understanding of how property traversal works and can be slightly more memory-efficient. Showing both approaches proves you understand object traversal and basic algorithm complexity tradeoffs.
Approach 1: Using Size/Length Properties
This approach involves using language-specific properties or methods that can quickly determine if an object or array has any elements. For objects, this often involves checking the number of keys, while for arrays it's about checking the length.
def is_object_empty(obj):
if isinstance(obj, dict) or isinstance(obj, list):
return len(obj) == 0
return Falseimport java.util.Map;
import java.util.List;
public class Solution {
public boolean isObjectEmpty(Map<String, Integer> obj) {
return obj.isEmpty();
}
public boolean isObjectEmpty(List<Integer> arr) {
return arr.isEmpty();
}
}#include <vector>
#include <map>
bool isObjectEmpty(const map<string, int>& obj) {
return obj.empty();
}
bool isObjectEmpty(const vector<int>& arr) {
return arr.empty();
}function isObjectEmpty(obj) {
if (Array.isArray(obj) || typeof obj === 'object') {
return Object.keys(obj).length === 0;
}
return false;
}bool isObjectEmpty(void* obj, int obj_type) {
if (obj_type == 0) { // Assuming 0 for object
return ((json_object*)obj)->length == 0;
} else { // Assuming 1 for array
return ((json_array*)obj)->size == 0;
}
}using System.Collections.Generic;
public class Solution {
public bool IsObjectEmpty(Dictionary<string, int> obj) {
return obj.Count == 0;
}
public bool IsObjectEmpty(List<int> arr) {
return arr.Count == 0;
}
}Python leverages the len() function which is O(1) for built-in collections like dicts and lists to check emptiness.
Time Complexity: O(1).
Space Complexity: O(1).
Approach 2: Using Iterator Method
This method relies on the use of iterators to quickly assess emptiness by attempting to iterate over the first element. If there is no element to begin with, it returns empty.
def is_object_empty_experimental(obj):
try:
next(iter(obj))
return False
except StopIteration:
return Trueimport java.util.Iterator;
public class Solution {
public boolean isObjectEmptyExperimental(Map<String, Integer> obj) {
return !obj.entrySet().iterator().hasNext();
}
public boolean isObjectEmptyExperimental(List<Integer> arr) {
return !arr.iterator().hasNext();
}
}#include <unordered_map>
bool isObjectEmptyExperimental(const std::unordered_map<std::string, int>& obj) {
return obj.begin() == obj.end();
}
#include <vector>
bool isObjectEmptyExperimental(const std::vector<int>& arr) {
return arr.begin() == arr.end();
}function isObjectEmptyExperimental(obj) {
for (let _ in obj) {
return false;
}
return true;
}bool isObjectEmptyExperimental(const json_object* obj) {
if (json_object_iterator_begin(obj) == json_object_iterator_end(obj)) {
return true;
}
return false;
}using System.Collections.Generic;
public class Solution {
public bool IsObjectEmptyExperimental(Dictionary<string, int> obj) {
return !obj.GetEnumerator().MoveNext();
}
public bool IsObjectEmptyExperimental(List<int> arr) {
return !arr.GetEnumerator().MoveNext();
}
}Python's iterators can be used to see if any elements are present by attempting to fetch the next element. This solution raises StopIteration if empty.
Time Complexity: O(1).
Space Complexity: O(1).
Approach 3: Default Approach
function isEmpty(obj: Record<string, any> | any[]): boolean {
for (const x in obj) {
return false;
}
return true;
}Complexity comparison
| Approach | Complexity |
|---|---|
| Using Size/Length Properties | Time Complexity: O(1). |
| Using Iterator Method | Time Complexity: O(1). |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Using Size/Length Properties | O(n) | O(1) | Most readable solution; preferred in interviews and common production code. |
| Using Iterator Method | O(n) | O(1) | Useful when you want early exit without allocating a list of keys. |
Frequently asked questions
Is Is Object Empty easy or hard?
Is Object Empty is classified as an Easy problem. It tests familiarity with basic object operations, iteration, and built-in language utilities rather than complex algorithms.
Is Object Empty Python/Java solution
In Python, you can check emptiness using len(obj) == 0 for dictionaries or lists. In Java, checking map.isEmpty() or collection.isEmpty() achieves the same goal. The underlying complexity remains O(n) in the worst case depending on implementation details.
How to solve Is Object Empty in O(n)?
Iterate over the object's keys and determine whether any element exists. Using Object.keys(obj).length === 0 or a for...in loop both work. The algorithm scans the properties once, resulting in O(n) time and O(1) extra space.
What is the best approach for Is Object Empty?
The most common approach checks the number of keys using a built-in helper such as Object.keys(obj).length in JavaScript. If the length is zero, the object is empty. This runs in O(n) time because all keys may be scanned, with O(1) additional space. It is concise and widely expected in interviews.
Is Is Object Empty asked at Google/Amazon/Meta?
Object and dictionary inspection problems appear frequently in interviews at companies like Google, Amazon, and Meta, especially in JavaScript-focused roles. While this exact problem may vary, checking whether a structure contains elements is a common fundamental task.
What data structure is used in Is Object Empty?
The problem operates on objects or associative containers, similar to hash maps or dictionaries. These structures store key-value pairs and allow iteration over keys to determine whether any entries exist.
What is the time complexity of Is Object Empty?
The time complexity is O(n), where n is the number of keys or elements in the object or array. Methods like Object.keys() or iteration loops may need to inspect every property in the worst case. Space complexity is typically O(1) excluding temporary structures created by built-in helpers.
