Check if Object Instance of Class solution and explanation
5 more videos on this problem
Check if Object Instance of Class - Leetcode 2618 - JavaScript 30-Day ChallengeNeetCodeIO · 11:58 · 4K views
Check if Object Instance of Class - LeetCode 2618 - JavaScript - JS 30 Day Challenge Day 25Alpha-Code · 14:10 · 173 views
2618. Check if Object Instance of Class - Day 25/30 Leetcode Javascript ChallengeProgramming Live with Larry · 14:46 · 159 views
Leetcode Grind - День 74. Check if Object Instance of ClassMark Brut [IT] · 1:03:25 · 125 views
Days 25. LeetCode 2618. Check if Object Instance of Class. Daily JS challengeКанал про вирішення ЛітКод Українською · 11:45 · 107 views
Mastering Instance Checks in JavaScript: Day 25 of Leetcode's 30-day JS Challenge | 2618vanAmsen · 5:25 · 89 views
The problem
Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.
Example 1:
Input: func = () => checkIfInstanceOf(new Date(), Date) Output: true Explanation: The object returned by the Date constructor is, by definition, an instance of Date.
Example 2:
Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
Output: true
Explanation:
class Animal {};
class Dog extends Animal {};
checkIfInstanceOf(new Dog(), Animal); // true
Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.
Example 3:
Input: func = () => checkIfInstanceOf(Date, Date) Output: false Explanation: A date constructor cannot logically be an instance of itself.
Example 4:
Input: func = () => checkIfInstanceOf(5, Number) Output: true Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".
Approach overview
Problem Overview: You are given an object and a class (constructor). The task is to determine whether the object is an instance of that class. In other words, check whether the object's inheritance chain contains the provided class constructor.
Approach 1: Use Language-Specific Instance Checking (Time: O(1), Space: O(1))
Most languages provide a built‑in operator or function for checking class membership. In JavaScript you use instanceof, Python provides isinstance(), Java uses instanceof, and C# provides the is operator. These utilities internally inspect the object's type metadata or prototype chain and return a boolean result. Because the runtime handles the check natively, the operation is effectively constant time for typical use cases and requires no additional memory.
This approach is the most reliable and concise. It correctly handles inheritance, meaning subclasses also count as instances of the parent class. When writing production code or solving interview problems, this is almost always the preferred solution because it uses the language’s built‑in type system instead of re‑implementing it manually.
Approach 2: Manual Prototype Chain Walking (Time: O(h), Space: O(1))
In JavaScript, objects inherit from other objects through a prototype chain. Each object has an internal [[Prototype]] reference accessible through Object.getPrototypeOf() or __proto__. To determine if an object is an instance of a constructor, you can repeatedly move up this chain and compare each prototype with constructor.prototype.
The algorithm is straightforward: start with the object's prototype, iterate upward using Object.getPrototypeOf(), and stop if you either find the target prototype or reach null. If the target appears anywhere in the chain, the object is an instance of that class. The runtime cost depends on the depth of the inheritance chain (h), which is usually small but technically linear in the chain length.
This approach demonstrates a deeper understanding of how JavaScript implements object-oriented programming through prototypes rather than classical classes. It’s useful when implementing custom type utilities or when interviewers want to see knowledge of the prototype chain itself.
Recommended for interviews: Use the language’s built‑in instance check. Interviewers expect you to recognize the native operator (instanceof, isinstance, etc.) because it’s concise and idiomatic. The manual prototype traversal is still valuable to discuss because it shows you understand how instance checking works under the hood.
Approach 1: Approach 1: Use Language-Specific Instance Checking
In this approach, we make use of direct language features to determine if an object is an instance of a given class. Most programming languages have built-in operators or functions to check instanceof relationships, such as 'instanceof' in JavaScript, or 'isinstance' in Python.
def check_if_instance_of(obj, cls):
return isinstance(obj, cls)public static boolean checkIfInstanceOf(Object obj, Class<?> cls) {
return cls.isInstance(obj);
}function checkIfInstanceOf(obj, cls) {
return obj instanceof cls;
}// C does not have built-in object-oriented features like instanceof. Instead, this would be handled through custom implementations or a different language.public static bool CheckIfInstanceOf(object obj, Type type) {
return type.IsInstanceOfType(obj);
}In Python, 'isinstance' is a built-in function used to check if an object is an instance or subclass of a class. It directly returns true or false based on the check.
Time Complexity: O(1)
Space Complexity: O(1)
Approach 2: Approach 2: Manual Prototype Chain Walking (JavaScript Specific)
This approach is specifically for JavaScript where we manually traverse the prototype chain of the object to check if the class prototype is found in the chain.
// C++ does not provide dynamic runtime type information similar to JavaScript's prototype chain traversal. Instead, RTTI (Run-Time Type Information) mechanisms in C++ such as 'dynamic_cast' or typeid can be used for known inheritance hierarchies, albeit with different constraints.function checkIfInstanceOf(obj, cls) {
if (obj === null || obj === undefined) return false;
let prototype = Object.getPrototypeOf(obj);
while (prototype) {
if (prototype === cls.prototype) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}// Similar to the first approach, C does not support object-oriented paradigms and prototype chains are not applicable.C++ employs extensive compile-time type checking and enforces static polymorphism, making prototype chain traversal as in JavaScript unsuitable and unavailable. Instead, C++ relies on virtual functions and RTTI features like 'dynamic_cast' for checked downcasting only within known hierarchical contexts.
Time Complexity: Not applicable
Space Complexity: Not applicable
Approach 3: Default Approach
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
if (classFunction === null || classFunction === undefined) {
return false;
}
while (obj !== null && obj !== undefined) {
const proto = Object.getPrototypeOf(obj);
if (proto === classFunction.prototype) {
return true;
}
obj = proto;
}
return false;
}
/**
* checkIfInstanceOf(new Date(), Date); // true
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Use Language-Specific Instance Checking | Time Complexity: O(1) |
| Approach 2: Manual Prototype Chain Walking (JavaScript Specific) | Time Complexity: Not applicable |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Language-Specific Instance Checking | O(1) | O(1) | Default choice. Uses built-in operators like instanceof or isinstance for fast and reliable type checks. |
| Manual Prototype Chain Walking | O(h) | O(1) | When implementing custom instance logic or demonstrating understanding of JavaScript prototype inheritance. |
Frequently asked questions
Is Check if Object Instance of Class easy or hard?
The problem is rated Medium because the concept appears simple but understanding how instance checks work internally can be tricky. The optimal solution is short using built-in operators, but explaining prototype traversal or inheritance mechanics requires deeper knowledge.
Check if Object Instance of Class Python/Java solution
Python solves the problem using isinstance(obj, ClassName), which checks the object's type and its parent classes. Java uses the instanceof operator, which returns true if the object belongs to the class or any subclass in its inheritance hierarchy.
How to solve Check if Object Instance of Class in O(1)?
Use the language's native instance checking operator. For example, JavaScript uses obj instanceof ClassName, Python uses isinstance(obj, ClassName), and Java also supports instanceof. These operations directly verify type relationships and run in constant time with no extra space.
What is the best approach for Check if Object Instance of Class?
The best approach is to use the language’s built-in instance checking feature such as JavaScript's instanceof, Python's isinstance(), Java's instanceof, or C#'s is operator. These are optimized runtime checks that verify whether the object's inheritance chain contains the given class. They run in O(1) time and require no additional memory.
Is Check if Object Instance of Class asked at Google/Amazon/Meta?
Problems involving type checking and object inheritance appear in interviews at companies that emphasize JavaScript or object-oriented fundamentals. Variants of prototype chain questions and instanceof behavior have been discussed in interviews at companies like Meta and frontend-heavy roles at large tech firms.
What data structure is used in Check if Object Instance of Class?
The core concept relies on the class inheritance hierarchy or prototype chain. In JavaScript this is implemented through linked prototype references between objects, forming a chain that can be traversed until the root object is reached.
What is the time complexity of Check if Object Instance of Class?
Using built-in instance checking typically runs in O(1) time with O(1) space because the runtime directly inspects the object's type information. A manual prototype-chain traversal solution in JavaScript takes O(h) time where h is the height of the prototype chain.
