LeetCode 2665: Counter II Solution
Master LeetCode problem 2665 (Counter II), a easy 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.
2665. Counter II
Problem Explanation
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
currentto store the current value, which is set toinit. - Return an object with three functions:
increment: Increment thecurrentvalue by 1 and return it.decrement: Decrement thecurrentvalue by 1 and return it.reset: Set thecurrentvalue back toinitand 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
currentvalue.
- The space complexity is O(1) as we only need a constant amount of space to store the
:
Solution Code
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);
}Try It Yourself
Loading code editor...
Frequently Asked Questions
How to solve LeetCode 2665 (Counter II)?
This page provides optimized solutions for LeetCode problem 2665 (Counter II) 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 2665 (Counter II)?
The time complexity for LeetCode 2665 (Counter II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2665 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2665 in Java, C++, or Python.