Basics
UTF-16 and UTF-32
Fixed and variable width encodings used in modern environments.
Time Complexity
O(1)
Space Complexity
O(2-4 bytes)
Interactive Visualization
Technical Guide
UTF-16 uses either 2 or 4 bytes per character and is the internal format for JavaScript and Java. UTF-32 uses exactly 4 bytes for every single character. UTF-32 is easier for O(1) indexing but consumes vast amounts of memory. UTF-16 is a middle ground but introduced 'Surrogate Pairs', where one logical character is represented by two 16-bit storage units.
Logical Phases
- 1UTF-16 maps the Basic Multilingual Plane (common chars) to 2 bytes.
- 2Extended characters (Emojis) use two 16-bit units (Surrogates).
- 3UTF-32 maps every Unicode code point directly to a 32-bit integer.
- 4Choosing UTF-32 for algorithms where memory is cheap but indexing speed is critical.
Implementation
// UTF-16 surrogate pair
'🚀'.length; // 2 unitsExpert Pitfalls
UTF-16 is variable-width just like UTF-8, but often mistaken for fixed-width.