Calculator with Method Chaining solution and explanation
9 more videos on this problem
Calculator with Method Chaining | Leetcode 2726 | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 6:22 · 1K views
#day30 |2726. Calculator with Method Chaining | Leetcode-2726 | Method Chaining is JS | Array in JSCoding with Ankita · 12:04 · 756 views
LeetCode problem #2726 (JavaScript)Code of Thunder · 12:13 · 283 views
#Leetcode 2726 Chaining Calculator 🚀 Day 30 👨💻 30Days of JavaScript Challenge LeetCodeRajat Talesra · 3:22 · 121 views
LeetCode problems #2726 (JavaScript), #897 (Ruby)Code of Thunder · 19:30 · 98 views
30 - Calculator with Method Chaining: Mastering Method ChainingJanja Programmers · 10:52 · 90 views
2726. Calculator with Method Chaining | JavaScript ClassCodeCrafting with Vishnu · 5:09 · 69 views
Master JavaScript with LeetCode: 30-Day Challenge || Calculator with Method Chaining (JSON - Day-30)Rishi Raj · 8:36 · 42 views
#LeetCode 2726 | Calculator with Method Chaining #JavaSleepy Cracker · 2:46 · 16 views
Day 30 – Calculator with Method Chaining in JavaScript LeetCode 2726 Classes & Error HandlingCode and Click · 4:32 · 9 views
The problem
Design a Calculator class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator class constructor should accept a number which serves as the initial value of result.
Your Calculator class should have the following methods:
add- This method adds the given numbervalueto theresultand returns the updatedCalculator.subtract- This method subtracts the given numbervaluefrom theresultand returns the updatedCalculator.multiply- This method multiplies theresultby the given numbervalueand returns the updatedCalculator.divide- This method divides theresultby the given numbervalueand returns the updatedCalculator. If the passed value is0, an error"Division by zero is not allowed"should be thrown.power- This method raises theresultto the power of the given numbervalueand returns the updatedCalculator.getResult- This method returns theresult.
Solutions within 10-5 of the actual result are considered correct.
Example 1:
Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7] Output: 8 Explanation: new Calculator(10).add(5).subtract(7).getResult() // 10 + 5 - 7 = 8
Example 2:
Input: actions = ["Calculator", "multiply", "power", "getResult"], values = [2, 5, 2] Output: 100 Explanation: new Calculator(2).multiply(5).power(2).getResult() // (2 * 5) ^ 2 = 100
Example 3:
Input: actions = ["Calculator", "divide", "getResult"], values = [20, 0] Output: "Division by zero is not allowed" Explanation: new Calculator(20).divide(0).getResult() // 20 / 0 The error should be thrown because we cannot divide by zero.
Constraints:
actionsis a valid JSON array of stringsvaluesis a valid JSON array of numbers2 <= actions.length <= 2 * 1041 <= values.length <= 2 * 104 - 1actions[i]is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"- First action is always "Calculator"
- Last action is always "getResult"
Approach overview
Problem Overview: Design a calculator object that supports chained arithmetic operations such as add(), subtract(), multiply(), and divide(). Each method updates an internal value and returns the calculator instance so the next operation can be called in the same expression.
Approach 1: Class Design with Method Chaining (O(1) time per operation, O(1) space)
This approach uses a simple class that stores the current numeric value as internal state. Each arithmetic method modifies that value and then returns self (Python) or this (Java). Returning the same object enables chaining: calc.add(5).multiply(2).subtract(3). Internally, each operation performs a constant-time arithmetic update, so the time complexity per call is O(1) and the class only stores one number, giving O(1) space. This pattern is common in object-oriented design and relies on the concept of returning the current instance from methods.
The key insight is that the calculator never creates new objects for each step. Instead, it mutates the stored value and returns the same instance. This keeps the implementation small and efficient while still providing a clean API. Division requires one extra check: if the divisor is zero, throw an exception to prevent invalid state.
Approach 2: Fluent Interface with Error Handling (O(1) time per operation, O(1) space)
A more structured variation follows the fluent interface design pattern. The class still stores the current value, but each method explicitly validates inputs and handles error cases. For example, divide() checks for zero and throws an exception, while other operations simply update the stored value. After validation and calculation, the method returns this so the chain continues.
This approach is common in JavaScript and C# APIs where fluent method calls improve readability and developer ergonomics. The implementation still performs constant-time arithmetic operations and uses constant memory. The difference lies in defensive checks and clearer API design, which is important when building reusable libraries or interview-quality class structures. The design also demonstrates understanding of class design and object-oriented programming patterns.
Recommended for interviews: The standard class with method chaining is what interviewers expect. It shows you understand how returning the current object enables chained calls and how to maintain internal state cleanly. Mentioning the fluent interface pattern and adding divide-by-zero validation demonstrates stronger API design thinking. The brute implementation proves you understand chaining mechanics, while the polished version shows production-level design awareness.
Approach 1: Class Design with Method Chaining
In this approach, we will design a Calculator class with a constructor that initializes the result. Each operation method will modify the object's state and return the Calculator object itself to allow method chaining. The method for division needs to handle division by zero gracefully by throwing an appropriate exception.
class Calculator:
def __init__(self, initial_value):
self.result = initial_value
def add(self, value):
self.result += value
return self
def subtract(self, value):
self.result -= value
return self
def multiply(self, value):
self.result *= value
return self
def divide(self, value):
if value == 0:
raise ValueError("Division by zero is not allowed")
self.result /= value
return self
def power(self, value):
self.result **= value
return self
def getResult(self):
return self.resultpublic class Calculator {
private double result;
public Calculator(double initialValue) {
this.result = initialValue;
}
public Calculator add(double value) {
this.result += value;
return this;
}
public Calculator subtract(double value) {
this.result -= value;
return this;
}
public Calculator multiply(double value) {
this.result *= value;
return this;
}
public Calculator divide(double value) {
if (value == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
this.result /= value;
return this;
}
public Calculator power(double value) {
this.result = Math.pow(this.result, value);
return this;
}
public double getResult() {
return this.result;
}
}In the Python solution, each method modifies self.result, a class attribute, and returns self to allow method chaining. The divide method checks for division by zero and raises a ValueError if encountered. The getResult() method returns the current result.
Time Complexity: O(1) for each operation since they all perform a constant amount of work.
Space Complexity: O(1) since we use only a fixed amount of space irrespective of input size.
Approach 2: Fluent Interface with Error Handling
This approach emphasizes clear error management alongside method chaining. Each mathematical function adjusts the internal result and returns the instance for seamless operation chaining. Special attention is paid to division, where an exception is thrown in case of dividing by zero, ensuring the program handles this gracefully.
class Calculator {
constructor(initialValue) {
this.result = initialValue;
}
add(value) {
this.result += value;
return this;
}
subtract(value) {
this.result -= value;
return this;
}
multiply(value) {
this.result *= value;
return this;
}
divide(value) {
if (value === 0) {
throw new Error("Division by zero is not allowed");
}
this.result /= value;
return this;
}
power(value) {
this.result **= value;
return this;
}
getResult() {
return this.result;
}
}public class Calculator {
private double result;
public Calculator(double initialValue) {
this.result = initialValue;
}
public Calculator Add(double value) {
this.result += value;
return this;
}
public Calculator Subtract(double value) {
this.result -= value;
return this;
}
public Calculator Multiply(double value) {
this.result *= value;
return this;
}
public Calculator Divide(double value) {
if (value == 0) {
throw new DivideByZeroException("Division by zero is not allowed");
}
this.result /= value;
return this;
}
public Calculator Power(double value) {
this.result = Math.Pow(this.result, value);
return this;
}
public double GetResult() {
return this.result;
}
}In the JavaScript implementation, each operation method updates the result attribute and returns the current instance to enable method chaining. The divide method checks for zero to prevent division by zero, throwing an Error as appropriate. The method getResult retrieves the current value of result.
Time Complexity: O(1) for each operation; each involves direct arithmetic with a constant time overhead.
Space Complexity: O(1) due to constant space usage regardless of input size.
Approach 3: Default Approach
class Calculator {
private x: number;
constructor(value: number) {
this.x = value;
}
add(value: number): Calculator {
this.x += value;
return this;
}
subtract(value: number): Calculator {
this.x -= value;
return this;
}
multiply(value: number): Calculator {
this.x *= value;
return this;
}
divide(value: number): Calculator {
if (value === 0) {
throw new Error('Division by zero is not allowed');
}
this.x /= value;
return this;
}
power(value: number): Calculator {
this.x **= value;
return this;
}
getResult(): number {
return this.x;
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Class Design with Method Chaining | Time Complexity: O(1) for each operation since they all perform a constant amount of work. |
| Fluent Interface with Error Handling | Time Complexity: O(1) for each operation; each involves direct arithmetic with a constant time overhead. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Class Design with Method Chaining | O(1) per operation | O(1) | Standard interview solution demonstrating method chaining using self/this |
| Fluent Interface with Error Handling | O(1) per operation | O(1) | When building production-style APIs with validation such as divide-by-zero checks |
Frequently asked questions
Is Calculator with Method Chaining easy or hard?
Calculator with Method Chaining is categorized as an Easy problem because it mainly tests understanding of classes and method chaining. The implementation is short, and the complexity is constant time and constant space.
Calculator with Method Chaining Python/Java solution
Python implementations return self from each method, while Java implementations return this. Both maintain an internal value field that gets updated after every operation. The chaining behavior works the same in both languages and runs in O(1) time per operation.
How to solve Calculator with Method Chaining in O(1)?
Create a calculator class with a variable storing the current result. Each method updates that variable using the requested arithmetic operation and returns the same instance (self or this). Because every operation is a constant-time arithmetic update, the complexity remains O(1) per call.
What is the best approach for Calculator with Method Chaining?
The standard solution uses a class that stores the current value and returns the same instance from every arithmetic method. Each method performs the operation, updates the internal state, and returns self or this so calls can be chained. This design runs in O(1) time per operation and O(1) space.
Is Calculator with Method Chaining asked at Google/Amazon/Meta?
Method chaining and fluent interface design appear in object-oriented design interviews at companies like Amazon, Google, and Meta. The exact problem may vary, but the concept of returning the current object to enable chained API calls is a common design pattern interviewers expect candidates to understand.
What data structure is used in Calculator with Method Chaining?
The solution primarily relies on object-oriented class design rather than a traditional data structure. The class maintains a single numeric state variable and exposes methods that modify it while returning the instance to support chaining.
What is the time complexity of Calculator with Method Chaining?
Each calculator operation such as add, subtract, multiply, or divide performs a single arithmetic update on the stored value. That makes the time complexity O(1) per method call and the space complexity O(1) because only one numeric value is stored.
