Layers of Logic

Foundation 02

String

An indexed sequence of characters, with immutability rules that depend on the language.

Core4 operations comparedJava · Python · C++

What the structure guarantees

Most string algorithms reason about positions just as array algorithms do. The important extra rule is immutability: Java and Python strings cannot be changed in place, so an apparent edit creates a new string.

How that model appears in code

Use StringBuilder in Java, a list of characters in Python, or mutable std::string operations in C++ when a loop must build or change text repeatedly.

String basics

String text = "level";
char first = text.charAt(0);
char last = text.charAt(text.length() - 1);

What gets more expensive as the input grows

OperationCostWhy
Read character iO(1)The character position is indexed directly.
Scan the stringO(n)Every character is inspected.
Create a substring of length kO(k)Modern runtimes usually copy those characters.
Concatenate repeatedlyUp to O(n²)Immutable strings may be copied after every append.

Choose it for the operations it makes cheap

Good fit

  • Character scans
  • Prefix and suffix checks
  • Two-pointer comparisons from both ends

Poor fit

  • Repeated in-place edits in immutable languages
  • Frequent insertion in the middle

Used by

Two PointersSliding Window

Errors that survive a first glance

  1. A character is not always a full user-visible symbol

    Unicode can represent one visible symbol with more than one code unit. Basic interview tasks often ignore this; production text handling cannot.

  2. Use content equality

    In Java, equals compares string contents; == compares references.

  3. Do not concatenate in a large loop

    Use a mutable builder when the output grows one piece at a time.