AlgoMaster Logo
AlgoMasterCalculate Hash Shard Loadmedium

Calculate Hash Shard Load

medium

Hash-based sharding splits records across database servers so that no single server stores every key. In this exercise, the integer key itself acts as the hash value.

Design a HashShardRouter class:

  • HashShardRouter() creates a stateless router.
  • int[] shardLoads(int[] keys, int numShards) returns the number of keys assigned to every shard.

Route each key to shard key % numShards. Return an array of length numShards, where result position i is the number of keys routed to shard i. Duplicate keys represent separate records and each contributes to the count. Include zero for any empty shard, and do not modify keys.

Example 1:

Input:

Output:

Explanation: Keys 3 and 6 route to shard 0; keys 1, 4, and 7 route to shard 1; keys 2, 5, and 8 route to shard 2.

Example 2:

Input:

Output:

Explanation: Keys 20 and 40 route to shard 0, and keys 10 and 30 route to shard 2. The other shards receive no keys.

Constraints

  • 0 <= keys.length <= 10^5
  • 0 <= keys[i] <= 10^9
  • 1 <= numShards <= 10^5
  • The sum of all returned loads equals keys.length.
  • At most 100 calls are made to shardLoads.
Hints

Loading...
CallReturns
new HashShardRouter()null
shardLoads([1,2,3,4,5,6,7,8], 3)[2,3,3]

Keys 3 and 6 route to shard 0; keys 1, 4, and 7 route to shard 1; keys 2, 5, and 8 route to shard 2.

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