Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

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.

  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.

:

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.