Basics
String Indexing Pitfalls
Why O(1) indexing is often a lie in modern string implementations.
Time Complexity
O(N)
Space Complexity
O(1)
Interactive Visualization
Technical Guide
In older systems, indexing `str[i]` was an O(1) operation because characters were always 1 byte. In the modern Unicode era, this is a dangerous trap. Accessing a string by index can return a partial byte or a partial surrogate pair, resulting in corrupted text. Modern high-performance string libraries often discourage index-based access in favor of iterators.
Logical Phases
- 1Recognizing that `str[i]` returns a code unit, not a character.
- 2Visualizing how an emoji takes multiple indices.
- 3Using high-level iterators to safely traverse multi-byte text.
- 4Pre-calculating an index-to-character map if O(1) access is needed.
Implementation
const text = 'A🌍C';
console.log(text[1]); // '�' (Broken!)Expert Pitfalls
Writing code that works for 'ABC' but crashes when a user enters an emoji.