Skip to content
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

Dangerous: str[1]

A
🌍
C
Intent (Char at 1)
🌍
Reality (Unit at 1)
0xD83D
"High Surrogate" - Corrupted!

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

  • 1
    Recognizing that `str[i]` returns a code unit, not a character.
  • 2
    Visualizing how an emoji takes multiple indices.
  • 3
    Using high-level iterators to safely traverse multi-byte text.
  • 4
    Pre-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.