OpenAI questions

Shard Rebalancing

OpenAIPhone screenHard

A cluster stores data in shards. Each shard has a unique string id and covers every integer key in an inclusive range [start, end]. Shards may overlap. A replication limit limit (an integer of at least 1) says each key may belong to at most limit shards.

Build Shards(limit).

Part 1: Rebalancing overlapping shards

Implement:

  • add_shard(shard_id, start, end) adds a shard. Returns nothing.
  • remove_shard(shard_id) removes the shard with that id, and does nothing if there is none. Returns nothing.
  • get_shards() returns the current shards as a list of [shard_id, start, end], sorted by (start, shard_id).
  • rebalance() changes the shards, returning nothing, so that every key is in at most limit shards.

Rebalancing follows these rules:

  • It may only move a shard's start to a larger value. A shard's end and id never change, shards are never split, and no shard is created.
  • A shard whose start moves past its end is removed.
  • Shards are handled in order of (start, shard_id), and earlier shards have priority: a shard keeps its range unless it would put some key in more than limit shards, and then its start moves right by the smallest amount that fixes it, counting only the earlier shards that were kept.
  • Every key covered before rebalancing is still covered afterward.
  1. Example 1
    init
    [1]
    operations
    [["add_shard",["A",0,100]],["add_shard",["B",80,180]],["rebalance",[]],["get_shards",[]]]
    Output
    [null,null,null,[["A",0,100],["B",101,180]]]

    Why: Keys 80 to 100 are in both shards. Shard A starts first and keeps its range, so B starts at 101. The limit is 1, so each key may be in only one shard.

Constraints

  • 1 <= limit <= 10
  • 0 <= start <= end <= 1000
  • Shard ids are non-empty strings; add_shard is never called with an id that is already present
  • 1 <= len(operations) <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question