AlgoMaster Logo
AlgoMasterCount Keys Moved by Reshardingmedium

Count Keys Moved by Resharding

medium

Modulo sharding is simple, but resizing the shard set can relocate many records. A key stored on shard key % oldShards must move when its destination under newShards has a different index.

Design a ModuloReshardingAnalyzer class:

  • ModuloReshardingAnalyzer() creates a stateless analyzer.
  • int keysMoved(int[] keys, int oldShards, int newShards) returns the number of records whose shard index changes.

Each entry in keys represents one record. Duplicate keys therefore count separately. A record moves exactly when key % oldShards != key % newShards. Do not modify keys.

Example 1:

Input:

Output:

Explanation: Keys 0, 1, and 2 keep their shard indices. Keys 3 through 7 change destination, so five records move.

Example 2:

Input:

Output:

Explanation: Keys 10 and 30 move from shard 2 to shard 0. Keys 20 and 40 remain on shard 0.

Constraints

  • 0 <= keys.length <= 10^5
  • 0 <= keys[i] <= 10^9
  • 1 <= oldShards, newShards <= 10^5
  • At most 100 calls are made to keysMoved.
Hints

Loading...
CallReturns
new ModuloReshardingAnalyzer()null
keysMoved([0,1,2,3,4,5,6,7], 3, 4)5

Only keys 0, 1, and 2 keep the same shard index. The other five keys move.

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