Foundation 02
String
An indexed sequence of characters, with immutability rules that depend on the language.
Mental model
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.
Implementation
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);text = "level"
first = text[0]
last = text[-1]string text = "level";
char first = text[0];
char last = text[text.size() - 1];Operation costs
What gets more expensive as the input grows
O(1)The character position is indexed directly.O(n)Every character is inspected.O(k)Modern runtimes usually copy those characters.Up to O(n²)Immutable strings may be copied after every append.Tradeoffs
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
Common mistakes
Errors that survive a first glance
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.
Use content equality
In Java, equals compares string contents; == compares references.
Do not concatenate in a large loop
Use a mutable builder when the output grows one piece at a time.