Introduction to Strings Resource - aloalgo

Introduction to Strings

A string is a sequence of characters. In most programming languages, strings are immutable, meaning once created, they cannot be modified. This has important implications for time complexity.

String Basics

Why Immutability Matters

Since strings are immutable, concatenation creates a new string each time. Concatenating n single characters one by one is O(n²), not O(n).

Common String Operations

Slicing

Searching

Modifying (Creates New String)

Splitting and Joining

Common String Patterns

Pattern 1: Character Frequency

Pattern 2: Two Pointers

Use two pointers moving toward each other for palindrome checks, or moving in the same direction for other patterns.

Pattern 3: Sliding Window

Find substrings with certain properties using a sliding window.

Pattern 4: String Building

Build strings efficiently using a list and join at the end.

Pattern 5: String Matching

Useful String Methods

Time Complexity Reference

OperationTimeNotes
Access s[i]O(1)
Slice s[i:j]O(j-i)Creates new string
Concatenation +O(n+m)Creates new string
join()O(n)Total length of strings
find/indexO(n*m)n=text, m=pattern
in operatorO(n*m)Same as find
split()O(n)
replace()O(n)Creates new string

Common Interview Tips

  1. Remember strings are immutable: Use list for building strings, then join at the end for O(n) instead of O(n²).
  2. Use Counter for frequency problems: It's cleaner and handles edge cases automatically.
  3. Consider ASCII values: For character math, use ord() and chr(). E.g., ord('a') - ord('A') = 32.
  4. Two pointers for palindromes: Compare from both ends moving inward.
  5. Sliding window for substrings: Maintain a window with certain properties.
Was this helpful?
© 2026 aloalgo. All rights reserved.