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

Easy

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.

  1. Algorithm:

    • Initialize a variable current to store the current value, which is set to init.
    • Return an object with three functions:
      • increment: Increment the current value by 1 and return it.
      • decrement: Decrement the current value by 1 and return it.
      • reset: Set the current value back to init and return it.
  2. Time Complexity:

    • The time complexity for each operation (increment, decrement, reset) is O(1) since they involve simple arithmetic operations.
  3. Space Complexity:

    • The space complexity is O(1) as we only need a constant amount of space to store the current value.

:

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.

Back to LeetCode Solutions