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 ringremoveServer(serverId)- Remove a server from the ringgetServer(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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code