Design Patterns: Creational · Coding problem
Implement a Singleton Class
A free coding problem from the Singleton Pattern skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
Implement Solution as a classic lazily-initialized Singleton: getInstance() must always return the same shared instance, constructing it only the first time it's called.
To make "same instance" observable, the class also tracks a running count via increment()/getCount() - if every call really returns the same object, that count keeps accumulating across calls; if a fresh object were returned each time, the count would never rise above 1.
In Python: the methods are the classmethod get_instance(), increment() and get_count(). Python has no private constructors, so nothing stops a call to Solution() - the class keeps the shared instance in a class attribute, and get_instance() is the documented way in.
Example
Input:
6
INC INC INC INC INC GET
Output: 5
Given q space-separated operations (INC or GET), apply each one through Solution.getInstance() and print the result of every GET, one per line.
Constraints
1 <= q <= 10^4
How it's graded
- Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Singleton Pattern
Solve it Implement a Singleton Class free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime