CATEGORY 1 OF 13

String Manipulation

Master the fundamental string operations that appear in nearly every coding problem: traversal, slicing, searching, and transformation.

Time: O(n)
Space: O(n)

Learn & Reference

Understanding the Pattern

String Manipulation

Strings are one of the most common data types in programming. Nearly every coding problem involves strings in some way, whether as input, output, or intermediate processing. Mastering basic string operations builds the foundation for more advanced patterns like two pointers, sliding window, and dynamic programming.

Core Operations

Traversal

Iterate through characters one at a time. Most string problems start here — process each character and build a result.

Slicing & Substrings

Extract portions of a string by index range. Essential for problems involving words, prefixes, and suffixes.

Searching

Find characters or substrings within a string. Know your language's built-in search methods to avoid writing manual loops.

Transformation

Convert between cases, replace characters, split/join, and reverse. These operations compose together to solve most string problems.

Key Principles

  1. Strings are immutable in most languages — build new strings instead of modifying in place (except Go byte slices and Java char arrays)
  2. Use built-in methods firstsplit, join, replace, trim are optimized and less error-prone than manual loops
  3. Watch for off-by-one errors — string indices are 0-based, and slicing end indices are exclusive
  4. Consider character encoding — ASCII vs Unicode matters for problems involving char codes or special characters

Common Problem Patterns

  • Character counting — frequency maps, finding unique/repeated characters
  • String building — construct output character by character
  • Two-pass approach — first pass gathers info, second pass builds result
  • In-place simulation — work with character arrays when mutation is needed

Common Mistakes

  1. Forgetting strings are immutable: Concatenating in a loop creates O(n²) time in many languages — use string builder or join
  2. Off-by-one in slicing: s[0:3] gives 3 characters (indices 0, 1, 2), not 4
  3. Not handling empty strings: Always check for empty input before processing
  4. Case sensitivity: Forgetting to normalize case when comparing characters
  5. Whitespace handling: Not trimming input or handling multiple consecutive spaces

When to Use

Reverse, rotate, or transform a string
Count or find specific characters
Check if a string is a palindrome
Compress or encode a string
Parse or split a string into parts
Compare strings character by character
Build a new string from rules or transformations
Process words within a sentence

Template

1# --- Iterate Characters ---
2for ch in s:
3 # process each character
4
5# --- Build String from Characters ---
6result = []
7for ch in s:
8 result.append(ch.upper())
9result_str = ''.join(result)
10
11# --- Process Words ---
12words = s.split()
13processed = [word.strip() for word in words]
14result = ' '.join(processed)
15
16# --- Character-by-Character Transform ---
17def transform(s):
18 return ''.join(
19 ch.upper() if ch.isalpha() else ch
20 for ch in s
21 )
{ }

Syntax Reference

1# === String Basics ===
2s = "hello"
3len(s) # length: 5
4s[0] # access: 'h'
5s[-1] # last char: 'o'
6s[1:4] # slice: 'ell'
7s[::-1] # reverse: 'olleh'
8
9# === Search & Check ===
10s.find('ll') # index of substring: 2 (-1 if not found)
11s.index('ll') # same but raises ValueError
12'ell' in s # contains: True
13s.startswith('he') # True
14s.endswith('lo') # True
15s.count('l') # occurrences: 2
16
17# === Transform ===
18s.upper() # 'HELLO'
19s.lower() # 'hello'
20s.capitalize() # 'Hello'
21s.title() # 'Hello' (each word)
22s.strip() # trim whitespace
23s.replace('l', 'r') # 'herro'
24s.split(' ') # split into list
25' '.join(['a', 'b']) # join: 'a b'
26
27# === Character Checks ===
28ch.isalpha() # letter?
29ch.isdigit() # digit?
30ch.isalnum() # letter or digit?
31ch.isspace() # whitespace?
32ord('a') # char code: 97
33chr(97) # code to char: 'a'
📋

Common Recipes

1# --- Reverse a String ---
2def reverse_string(s):
3 return s[::-1]
4
5# --- Count Character Frequency ---
6from collections import Counter
7def char_frequency(s):
8 return dict(Counter(s))
9
10# --- Check Palindrome ---
11def is_palindrome(s):
12 return s == s[::-1]
13
14# --- Capitalize Each Word ---
15def capitalize_words(s):
16 return ' '.join(word.capitalize() for word in s.split())
17
18# --- Remove Duplicate Characters (preserve order) ---
19def remove_duplicates(s):
20 seen = set()
21 result = []
22 for ch in s:
23 if ch not in seen:
24 seen.add(ch)
25 result.append(ch)
26 return ''.join(result)
O(n)

Complexity

OperationTimeNotes
Access char by indexO(1)Direct index access
ConcatenationO(n)Creates new string (immutable)
Slice / SubstringO(k)k = length of slice
Search (find/indexOf)O(n*m)n = string, m = pattern
Split / JoinO(n)Processes entire string
ReverseO(n)Must copy all characters
Replace allO(n)Scans entire string

Watch Out

  • Forgetting strings are immutable: Concatenating in a loop creates O(n²) time in many languages — use string builder or join
  • Off-by-one in slicing: `s[0:3]` gives 3 characters (indices 0, 1, 2), not 4
  • Not handling empty strings: Always check for empty input before processing
  • Case sensitivity: Forgetting to normalize case when comparing characters
  • Whitespace handling: Not trimming input or handling multiple consecutive spaces