AlgoMaster Logo
AlgoMasterAdvance a Lamport Logical Clockmedium

Advance a Lamport Logical Clock

medium

A Lamport clock assigns increasing logical timestamps to local events and received messages. A receive event must be ordered after both the receiver's previous event and the sender's timestamp.

Design a LamportClockSimulator class:

  • LamportClockSimulator() creates a stateless simulator.
  • int[] timestamps(int[] incoming) returns the local clock after each event.

The local clock starts at 0 for every call. Process incoming in order:

  • incoming[i] == 0 represents a local event. Increment the clock by 1.
  • incoming[i] > 0 represents a received message timestamp. Set the clock to max(clock, incoming[i]) + 1.

Append the updated clock after each event.

Example 1:

Input:

Output:

Explanation: The first local event gets timestamp 1. Receiving timestamp 5 produces 6, and the next local event produces 7.

Example 2:

Input:

Output:

Explanation: The received timestamps 3 and 7 make their corresponding local receive events occur at 4 and 8.

Constraints

  • 0 <= incoming.length <= 10^5
  • 0 <= incoming[i] <= 10^9
  • 0 is reserved for a local event; positive values are received timestamps.
  • Every returned timestamp fits in a signed 32-bit integer.
  • At most 100 calls are made to timestamps.
Hints

Loading...
CallReturns
new LamportClockSimulator()null
timestamps([0,5,0])[1,6,7]

The local event produces 1. Receiving timestamp 5 advances the clock to 6, and the final local event increments it to 7.

Run checks these cases. Submit also runs a larger hidden set.