To Be Or Not To Be solution and explanation
9 more videos on this problem
2704. To Be Or Not To Be - Leetcode JavaScript Solution with ExplanationEndeavour Monk · 5:58 · 9K views
To Be Or Not To Be | Leetcode 2704 | Object Literals in JS | 30 Days of JavaScript #javascriptLearn With Chirag · 17:29 · 5K views
To Be Or Not To Be | 30 Days of JavaScript | LEETCODE 2704code Explainer · 5:00 · 2K views
#day3 | 2704. To Be Or Not To Be| 30 Days of JavaScript| Leetcode-2704 | 30 Days Challenge| ClosuresCoding with Ankita · 10:51 · 2K views
To Be Or Not To Be javascript || DAY 3 LEETCODE 2704 #30daysofjavascriptCodingWoding · 2:07 · 542 views
Leetcode | Javascript Fundamentals | Method Chaining | 2704. To Be Or Not To BeSoftware Interviews Prep · 11:06 · 531 views
30 days of JavaScript - To Be Or Not To BeCode With Bertrand · 18:37 · 278 views
LeetCode 2704 - Build a Custom Expect FunctionScott Hacks Code · 3:04 · 257 views
#Leetcode #2704. To Be Or Not To Be - Closure 🚀 Day 3 👨💻 30Days of JavaScript Challenge LeetCodeRajat Talesra · 3:58 · 224 views
2704. To Be Or Not To Be - Leetcode (Easy). 30 Days of JavaScript | День 3 | Быть или не бытьdev tsx · 2:20 · 166 views
The problem
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.
toBe(val)accepts another value and returnstrueif the two values===each other. If they are not equal, it should throw an error"Not Equal".notToBe(val)accepts another value and returnstrueif the two values!==each other. If they are equal, it should throw an error"Equal".
Example 1:
Input: func = () => expect(5).toBe(5)
Output: {"value": true}
Explanation: 5 === 5 so this expression returns true.
Example 2:
Input: func = () => expect(5).toBe(null)
Output: {"error": "Not Equal"}
Explanation: 5 !== null so this expression throw the error "Not Equal".
Example 3:
Input: func = () => expect(5).notToBe(null)
Output: {"value": true}
Explanation: 5 !== null so this expression returns true.
Approach overview
Problem Overview: You implement a tiny assertion utility similar to what testing frameworks provide. The function expect(val) returns an object with two methods: toBe(val2) and notToBe(val2). If the condition fails, the method throws an error. Otherwise it returns true. The challenge is mainly about structuring the returned behavior using language features such as closures or object-oriented programming.
Approach 1: Closure-Based Approach (O(1) time, O(1) space)
The closure approach captures the original value inside the scope of expect. The function returns an object containing toBe and notToBe methods, and both methods reference the captured value. When toBe(val2) runs, it directly compares the stored value with val2. If they are strictly equal, return true; otherwise throw an error such as "Not Equal". The notToBe method performs the opposite check and throws an error like "Equal" when the values match. This works because closures preserve access to variables defined in the outer function even after that function finishes execution.
The key insight is that you do not need persistent state outside the function. The captured variable inside the closure behaves like private data. This makes the implementation concise and idiomatic in languages such as JavaScript or Python where functions can return objects containing nested functions.
Approach 2: Class-Based Approach (O(1) time, O(1) space)
The class-based design wraps the value inside an instance field. Instead of relying on lexical scope, the stored value becomes a property of the class object. The constructor receives the value, and the methods toBe and notToBe operate on that stored field.
During execution, expect(val) simply returns a new instance of the class. Each method performs a direct equality comparison with the stored value and throws the appropriate error when the condition fails. This approach mirrors how many testing libraries internally implement assertions. It fits naturally in strongly object-oriented languages such as C++, Java, and C# where encapsulation through classes is the standard pattern.
The advantage is structural clarity. State and behavior are grouped inside a single class, which makes the implementation straightforward when closures are less idiomatic or unavailable.
Recommended for interviews: The closure-based implementation is typically the expected answer when the problem is asked in JavaScript because it demonstrates understanding of closures and lexical scope. The class-based approach is equally correct and often preferred in languages centered around object-oriented design. Interviewers mainly look for correct comparison logic, proper error handling, and a clean API design.
Approach 1: Closure-Based Approach
The closure-based approach makes use of JavaScript's closure capabilities to encapsulate the comparison logic within the returned object. The main idea here is to utilize closures to maintain the original value passed to the expect function, and then provide methods that perform the respective comparisons. This approach leverages the benefits of closures to maintain a clean and functional interface.
class Expect:
def __init__(self, val):
self.val = val
def toBe(self, value):
if self.val == value:
return True
else:
raise ValueError('Not Equal')
def notToBe(self, value):
if self.val != value:
return True
else:
raise ValueError('Equal')
# Usage
# expect = lambda x: Expect(x)function expect(val) {
return {
toBe: function(value) {
if (val === value) {
return true;
} else {
throw new Error('Not Equal');
}
},
notToBe: function(value) {
if (val !== value) {
return true;
} else {
throw new Error('Equal');
}
}
};
}In Python, we use a class to mimic the behavior of closures. The class Expect holds the value in its instance variable val. The methods toBe and notToBe perform the same checks and raise exceptions if conditions are not met. This is a good example of using OOP principles to simulate a closure-like behavior in Python.
Time Complexity: O(1) for both toBe and notToBe methods.
Space Complexity: O(1) since we're only storing one additional value.
Approach 2: Class-Based Approach
The class-based approach in languages like C++, C#, and Java exploits object-oriented programming features to achieve encapsulation and method binding. Here, the idea is to define a class that keeps track of the initial value and provides methods that can be invoked on it to perform the required checks. This method is beneficial for languages where closures don't exist or are cumbersome to implement, maintaining a clear object-oriented design.
public class Expect {
private Object val;
public Expect(Object val) {
this.val = val;
}
public boolean toBe(Object value) {
if (val.equals(value)) {
return true;
}
throw new RuntimeException("Not Equal");
}
public boolean notToBe(Object value) {
if (!val.equals(value)) {
return true;
}
throw new RuntimeException("Equal");
}
}
// Usage:
// new Expect(5).toBe(5);#include <stdexcept>
class Expect {
public:
Expect(int val) : val_(val) {}
bool toBe(int value) {
if (val_ == value) {
return true;
}
throw std::runtime_error("Not Equal");
}
bool notToBe(int value) {
if (val_ != value) {
return true;
}
throw std::runtime_error("Equal");
}
private:
int val_;
};
// Usage:
// Expect(5).toBe(5);public class Expect {
private object val;
public Expect(object val) {
this.val = val;
}
public bool ToBe(object value) {
if (val.Equals(value)) {
return true;
}
throw new System.Exception("Not Equal");
}
public bool NotToBe(object value) {
if (!val.Equals(value)) {
return true;
}
throw new System.Exception("Equal");
}
}
// Usage:
// var result = new Expect(5).ToBe(5);In Java, the Expect class keeps the value to be compared against in an instance variable. The toBe and notToBe methods perform equality checks using equals. Java's exception handling is used to simulate the throw behavior of JavaScript.
Time Complexity: O(1) for both methods.
Space Complexity: O(1).
Approach 3: Default Approach
type ToBeOrNotToBe = {
toBe: (val: any) => boolean;
notToBe: (val: any) => boolean;
};
function expect(val: any): ToBeOrNotToBe {
return {
toBe: (toBeVal: any) => {
if (val !== toBeVal) {
throw new Error('Not Equal');
}
return true;
},
notToBe: (notToBeVal: any) => {
if (val === notToBeVal) {
throw new Error('Equal');
}
return true;
},
};
}
/**
* expect(5).toBe(5); // true
* expect(5).notToBe(5); // throws "Equal"
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Closure-Based Approach | Time Complexity: O(1) for both |
| Class-Based Approach | Time Complexity: O(1) for both methods. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Closure-Based Implementation | O(1) | O(1) | Best for JavaScript/Python when demonstrating closure and lexical scope concepts |
| Class-Based Implementation | O(1) | O(1) | Preferred in C++, Java, and C# where object-oriented patterns are standard |
Frequently asked questions
Is To Be Or Not To Be easy or hard?
LeetCode classifies this problem as Easy with an acceptance rate around 62%. The difficulty comes from understanding closures or designing a small assertion-style API rather than implementing a complex algorithm.
To Be Or Not To Be Python/Java solution
In Python, the solution can mimic the closure pattern by returning an object or nested functions that capture the value. In Java, C++, and C#, the typical approach is a class with methods toBe and notToBe that operate on a stored instance variable.
How to solve To Be Or Not To Be in O(1)?
Store the initial value when expect(val) is called. Then implement two methods: toBe(val2) and notToBe(val2). Each method performs a constant-time comparison and either returns true or throws an error if the assertion fails.
What is the best approach for To Be Or Not To Be?
The closure-based approach is the most common solution, especially in JavaScript. It captures the input value inside the expect function and returns methods that compare against it. Both toBe and notToBe run in O(1) time with O(1) space because they only perform a constant-time equality check.
Is To Be Or Not To Be asked at Google/Amazon/Meta?
The problem style appears in frontend or JavaScript-focused interview rounds where understanding closures and API design is tested. Similar assertion utility questions are common in interviews at companies that emphasize JavaScript fundamentals.
What data structure is used in To Be Or Not To Be?
No complex data structure is required. The solution relies on either a closure that stores a single value or a class object containing that value as a field. The logic is built around simple equality checks.
What is the time complexity of To Be Or Not To Be?
All valid implementations run in O(1) time because the solution only performs a single equality comparison between two values. Space complexity is also O(1) since only one value is stored either in a closure or as a class field.
