Algorithm Create color from string
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Creating a color from a string is a deterministic hashing problem: the same input should always produce the same color, and different inputs should usually spread across the color space. The challenge is not only turning text into a number, but producing colors that are varied enough to distinguish visually and stable enough to use in a UI or chart.
Hash the String First
The usual pattern is to hash the string into an integer and then map that integer into a color model.
This is not a cryptographic hash, and it does not need to be. The goal is stable distribution, not security.
Map the Hash into a Color
One direct approach is to take bytes from the hash and interpret them as RGB.
This is easy, but the output quality can be uneven. Some generated colors are too dark, too light, or too gray to be useful in practice.
Prefer HSL When You Want Better Visual Control
HSL is often a better target because you can keep saturation and lightness in a readable range while varying only the hue.
This usually produces more balanced colors for tags, avatars, or category chips because the palette avoids extreme brightness values.
Tune for UI Readability
A pure algorithmic mapping is rarely enough. Real interfaces need constraints such as:
- avoid colors too close to white on light backgrounds
- avoid colors too close to black on dark backgrounds
- keep contrast acceptable for text overlays
- avoid nearly identical adjacent categories if the colors are shown together
That is why many production systems hash only the hue and then clamp saturation and lightness to a safe range. The result is less mathematically "free," but more useful.
Normalize the Input Before Hashing
Decide whether "Alice", "alice", and " alice " should map to the same color. If the answer is yes, normalize first.
This matters in user-facing systems where identifiers may differ only by casing or whitespace.
Common Pitfalls
- Using raw RGB bytes and ending up with many unreadable very dark or very pale colors.
- Treating the algorithm as security-related when it is only a deterministic mapping.
- Forgetting to normalize case and whitespace for strings that should map consistently.
- Assuming different strings must always produce visually distinct colors even though collisions are inevitable in a finite color space.
- Optimizing only for uniqueness and ignoring readability and contrast in the actual UI.
Summary
- Convert the string to a stable numeric hash first.
- Map the hash into a color model such as RGB or HSL.
- HSL is often better for UI work because saturation and lightness can be constrained.
- Normalize the input if equivalent strings should share a color.
- Design for readability, not just deterministic color generation.

