2665. Counter II LeetCode Solution

In this guide, you will get 2665. Counter II LeetCode Solution with the best time and space complexity. The solution to Counter II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Counter II solution in C++
  4. Counter II solution in Java
  5. Counter II solution in Python
  6. Additional Resources
2665. Counter II LeetCode Solution image

Problem Statement of Counter II

Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
The three functions are:

increment() increases the current value by 1 and then returns it.
decrement() reduces the current value by 1 and then returns it.
reset() sets the current value to init and then returns it.

Example 1:

Input: init = 5, calls = [“increment”,”reset”,”decrement”]
Output: [6,5,4]
Explanation:
const counter = createCounter(5);
counter.increment(); // 6
counter.reset(); // 5
counter.decrement(); // 4

Example 2:

Input: init = 0, calls = [“increment”,”increment”,”decrement”,”reset”,”reset”]
Output: [1,2,1,0,0]
Explanation:
const counter = createCounter(0);
counter.increment(); // 1
counter.increment(); // 2
counter.decrement(); // 1
counter.reset(); // 0
counter.reset(); // 0

Constraints:

-1000 <= init <= 1000
0 <= calls.length <= 1000
calls[i] is one of "increment", "decrement" and "reset"

Complexity Analysis

  • Time Complexity: Google AdSense
  • Space Complexity: Google Analytics

2665. Counter II LeetCode Solution in C++

type ReturnObj = {
  increment: () => number;
  decrement: () => number;
  reset: () => number;
};

function createCounter(init: number): ReturnObj {
  let cur = init;
  return {
    increment: () => ++cur,
    decrement: () => --cur,
    reset: () => (cur = init),
  };
}
/* code provided by PROGIEZ */

2665. Counter II LeetCode Solution in Java

N/A
// code provided by PROGIEZ

2665. Counter II LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.