LeetCode Problem Workspace
Calculator with Method Chaining
Design a Calculator class that supports method chaining for mathematical operations like addition, subtraction, multiplication, and more.
0
Topics
1
Code langs
0
Related
Practice Focus
Easy · Calculator with Method Chaining core interview pattern
Answer-first summary
Design a Calculator class that supports method chaining for mathematical operations like addition, subtraction, multiplication, and more.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Calculator with Method Chaining core interview pattern
The goal of this problem is to implement a Calculator class supporting basic mathematical operations using method chaining. Operations such as addition, subtraction, multiplication, division, and exponentiation should work consecutively with each call, and the result is fetched using getResult. Special attention is required to handle division by zero and provide correct error messages.
Problem Statement
You are tasked with implementing a Calculator class that supports basic mathematical operations such as addition, subtraction, multiplication, division, and exponentiation. The class should allow method chaining, meaning that operations can be executed consecutively in a single statement, and the result can be retrieved by calling getResult.
The Calculator class should initialize with a starting number and execute operations sequentially. It should handle special cases, such as division by zero, and return appropriate error messages when necessary. The final result of all operations should be returned by calling getResult.
Examples
Example 1
Input: actions = ["Calculator", "add", "subtract", "getResult"], values = [10, 5, 7]
Output: 8
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
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"
new Calculator(20).divide(0).getResult() // 20 / 0
The error should be thrown because we cannot divide by zero.
Constraints
- actions is a valid JSON array of strings
- values is a valid JSON array of numbers
- 2 <= actions.length <= 2 * 104
- 1 <= values.length <= 2 * 104 - 1
- actions[i] is one of "Calculator", "add", "subtract", "multiply", "divide", "power", and "getResult"
- First action is always "Calculator"
- Last action is always "getResult"
Solution Approach
Method Chaining
The Calculator class should store the current result and allow operations like add, subtract, multiply, divide, and power to modify this result. Each method should return the instance of the class to allow chaining of further operations.
Handling Edge Cases
The divide method should handle division by zero by returning an error message, such as 'Division by zero is not allowed'. This ensures that the solution accounts for all potential mathematical errors.
Efficient Result Retrieval
The getResult method should return the final calculated result. It should allow retrieving the result after any number of chained operations and be the final method in the chain.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(1) |
| Space | O(1) |
The time and space complexity of this problem is O(1) for each operation as the class stores only a single result at any point in time and each method performs a constant-time operation.
What Interviewers Usually Probe
- Look for an understanding of how method chaining works in object-oriented design.
- Check if edge cases, especially division by zero, are handled correctly.
- Ensure that the candidate writes clean, readable code with efficient handling of result retrieval.
Common Pitfalls or Variants
Common pitfalls
- Failing to return the Calculator instance in each method, thus breaking the chain.
- Not handling division by zero, which would lead to runtime errors or incorrect results.
- Misunderstanding the return behavior of
getResult, which should return the final result after all operations.
Follow-up variants
- Allowing for more advanced operations like square roots or logarithms.
- Adding support for complex numbers.
- Optimizing the implementation for large numbers of chained operations.
FAQ
What is method chaining in the Calculator problem?
Method chaining allows multiple operations to be executed consecutively on the same Calculator instance. Each operation returns the instance itself to allow for further operations.
How do I handle division by zero in the Calculator?
You should return an appropriate error message, such as 'Division by zero is not allowed', when the divide method encounters a zero divisor.
What is the purpose of the getResult method?
The getResult method returns the final result after performing all operations in the chain, allowing you to retrieve the calculated value.
How does GhostInterview assist with this problem?
GhostInterview helps you understand the core method chaining pattern and ensures you can handle errors like division by zero effectively.
What are the constraints in the Calculator problem?
The problem ensures that the first action is always 'Calculator' and the last is 'getResult'. It also provides constraints on the number of operations and input values.
Solution
Solution 1
#### TypeScript
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;
}
}