LeetCode 2618: Check if Object Instance of Class Solution

Master LeetCode problem 2618 (Check if Object Instance of Class), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2618. Check if Object Instance of Class

Medium

Problem Explanation

Explanation

To solve this problem, we can use the instanceof operator in Java and Python. However, for a more generic solution that works across different languages, we can implement our own function to check if an object is an instance of a given class or superclass by checking if the object has access to the class's methods.

Algorithm

  1. Check if the given value is an instance of the given class by attempting to call a method specific to that class on the value.
  2. If the method call is successful, return true, indicating that the object is an instance of the class.
  3. If the method call results in an error or exception, catch the error and return false, indicating that the object is not an instance of the class.

Time Complexity

The time complexity of this approach is O(1) as we are simply checking if the object has access to a method of the class.

Space Complexity

The space complexity of this approach is O(1) as we are not using any extra space that grows with the input.

Solution Code

public boolean checkIfInstanceOf(Object obj, Class<?> clazz) {
    try {
        clazz.cast(obj);
        return true;
    } catch (ClassCastException e) {
        return false;
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2618 (Check if Object Instance of Class)?

This page provides optimized solutions for LeetCode problem 2618 (Check if Object Instance of Class) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2618 (Check if Object Instance of Class)?

The time complexity for LeetCode 2618 (Check if Object Instance of Class) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2618 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2618 in Java, C++, or Python.

Back to LeetCode Solutions