Consistent Hashing Demo - Problem

Implement a simple consistent hashing ring for distributing keys across N servers.

In consistent hashing, both servers and keys are mapped to positions on a circular hash ring using a hash function. Each key is assigned to the first server found when moving clockwise around the ring from the key's position.

Your task is to implement a ConsistentHashRing class with the following operations:

  • addServer(serverId) - Add a server to the ring
  • removeServer(serverId) - Remove a server from the ring
  • getServer(key) - Find which server should handle the given key

For this problem, use a simple hash function: hash(x) = (x * 31) % 1000000 where x is the numeric value of the string (sum of ASCII values).

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["addServer","server1"],["addServer","server2"],["getServer","user123"],["removeServer","server1"],["getServer","user123"]]
Output: ["server1","server2"]
💡 Note: Add server1 and server2. user123 maps to server1. After removing server1, user123 now maps to server2.
Example 2 — Wrap Around Ring
$ Input: operations = [["addServer","A"],["addServer","B"],["getServer","key999"]]
Output: ["A"]
💡 Note: If key999 hashes beyond all servers, it wraps around to the first server on the ring.
Example 3 — No Servers Available
$ Input: operations = [["getServer","test"],["addServer","S1"],["getServer","test"]]
Output: ["S1"]
💡 Note: First getServer returns null (no servers), after adding S1, test maps to S1.

Constraints

  • 1 ≤ operations.length ≤ 1000
  • operations[i] is one of ["addServer", serverId], ["removeServer", serverId], or ["getServer", key]
  • serverId and key are strings of length 1-20 containing only letters and numbers
  • All server IDs are unique when added

Visualization

Tap to expand
INPUTALGORITHMRESULTHash Ringuser123→250kS1→300kS2→500kS3→800kOperations:addServer(S1)addServer(S2)getServer(user123)1Hash key position2Find servers ≥ key hash3Select closest clockwise4Return assigned serveruser123→ Server S1Key Distribution:Hash: 250,000Next server: S1 (300k)Clockwise assignmentKey Insight:Consistent hashing maps keys to the next server clockwise on a circular ring,ensuring minimal disruption when servers are added or removed.TutorialsPoint - Consistent Hashing Demo | Binary Search Approach
Asked in
Amazon 45 Google 38 Netflix 32 Facebook 28
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen