2665. Counter II
Explanation:
To implement the createCounter
function, we can use a closure that captures the init
value and maintains the current value. We will return an object with three functions: increment
, decrement
, and reset
. Each function will perform the required operation on the current value and return the updated value accordingly.
-
Algorithm:
- Initialize a variable
current
to store the current value, which is set toinit
. - Return an object with three functions:
increment
: Increment thecurrent
value by 1 and return it.decrement
: Decrement thecurrent
value by 1 and return it.reset
: Set thecurrent
value back toinit
and return it.
- Initialize a variable
-
Time Complexity:
- The time complexity for each operation (increment, decrement, reset) is O(1) since they involve simple arithmetic operations.
-
Space Complexity:
- The space complexity is O(1) as we only need a constant amount of space to store the
current
value.
- The space complexity is O(1) as we only need a constant amount of space to store the
:
class Counter {
int current;
public Counter(int init) {
this.current = init;
}
public int increment() {
return ++current;
}
public int decrement() {
return --current;
}
public int reset() {
return current = current;
}
}
public Counter createCounter(int init) {
return new Counter(init);
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.