#2618
Check if Object Instance of Class
MediumPrototype ChainInstance Checking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of manually traversing the prototype chain, we can use the built-in 'instanceof' operator in JavaScript, which is optimized for this purpose. This allows us to check if an object is an instance of a class or its superclass efficiently.
⚙️
Algorithm
3 steps- 1Step 1: If the value is undefined or null, return false.
- 2Step 2: Use the instanceof operator to check if the object is an instance of the class.
- 3Step 3: Return the result of the instanceof check.
solution.py4 lines
1def checkIfInstanceOf(obj, cls):
2 if obj is None:
3 return False
4 return isinstance(obj, cls)ℹ
Complexity note: This complexity is linear because we are leveraging the built-in mechanisms that are optimized for checking instances.
- 1Understanding the prototype chain is crucial for working with instances in JavaScript.
- 2Using built-in operators like instanceof can greatly simplify and optimize your solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.