Problem · Hash Table

Simulate a Reference-Counted Smart Pointer

Learn this problem
MediumNvidia logoNvidiaFULLTIMEPHONE SCREEN

Problem 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 by h, create the unique positive object id, and make h its sole owner.
  • copy target source: release target, then make it share source. Copying an empty source makes the target empty.
  • move target source: if the handles differ, release target, transfer ownership from source, and leave source empty.
  • reset h: release h and leave it empty.
  • get h: emit get:id, or get:-1 when h is empty.
  • use_count h: emit use_count:count; an empty handle has count 0.

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

  • operations contains at least one valid operation.
  • Handle names are non-empty tokens without spaces.
  • Every create uses a positive object ID that does not appear in another create.
  • All object IDs fit in a signed 32-bit integer.
  • Operations are processed in their given order.

More Nvidia problems

drafts saved locally
public String[] simulateSharedPointer(String[] operations) {
  // write your code here
}
operations["create a 7","copy b a","use_count a","get b","reset a","use_count b"]
expected["use_count:2", "get:7", "use_count:1", "destroy:7"]
checking account