Simulate a Reference-Counted Smart Pointer
Learn this problemProblem statement
Simulate shared-ownership smart pointers over a finite sequence of operations on named handles. All handles start empty. A managed object is destroyed exactly once when its strong reference count reaches 0.
Each operation is one space-separated string:
create h id: release the value currently owned byh, create the unique positive objectid, and makehits sole owner.copy target source: releasetarget, then make it sharesource. Copying an empty source makes the target empty.move target source: if the handles differ, releasetarget, transfer ownership fromsource, and leavesourceempty.reset h: releasehand leave it empty.get h: emitget:id, orget:-1whenhis empty.use_count h: emituse_count:count; an empty handle has count0.
Copy or move assignment from a handle to itself is a no-op. Whenever a release destroys an object, immediately emit destroy:id. After the final operation, destroy handles in reverse order of their first appearance and emit any resulting destruction events. Return all emitted strings in chronological order.
Function
simulateSharedPointer(operations: String[]) → String[]Examples
Example 1
operations = ["create a 7","copy b a","use_count a","get b","reset a","use_count b"]return = ["use_count:2","get:7","use_count:1","destroy:7"]After the copy, a and b share object 7. Resetting a leaves one owner, and final cleanup destroys the object.
Example 2
operations = ["create a 1","create b 2","move a b","get b","get a","use_count a"]return = ["destroy:1","get:-1","get:2","use_count:1","destroy:2"]Moving b into a first destroys object 1. Handle b becomes empty, and final cleanup destroys object 2.
Example 3
operations = ["create a 5","copy a a","move a a","use_count a","reset a","get a"]return = ["use_count:1","destroy:5","get:-1"]Both self-assignments are no-ops. Resetting the only owner destroys object 5, and the final query observes an empty handle.
Constraints
operationscontains at least one valid operation.- Handle names are non-empty tokens without spaces.
- Every
createuses a positive object ID that does not appear in anothercreate. - All object IDs fit in a signed 32-bit integer.
- Operations are processed in their given order.