π§±
Core Data Structures
Slicing Β· string methods Β· ASCII tricks
04. Arrays & Strings
Arrays and strings are the foundation for two-pointer, palindrome, and anagram problems. Master slicing, the string methods you'll use every day, and ASCII-based tricks.
arraystringtwo-pointer
Duration
β± ~1 hour
Level
π Beginner
Prerequisite
π― Basics track
OUTCOME
Transform any string/array problem into a clean Python solution.
What you'll learn
- 1Use slicing, reversing, and stepping confidently
- 2Apply common string methods: split, join, strip, replace, find
- 3Solve palindrome and anagram problems
Overview
Most string problems boil down to slicing, indexing, and a small set of methods. ASCII tricks (ord/chr arithmetic) handle Caesar ciphers, character counts, and similar tasks elegantly.
Core Concepts
1. Slicing
python
s = 'abcdefg'
s[0] # 'a'
s[-1] # 'g'
s[2:5] # 'cde'
s[:3] # 'abc'
s[3:] # 'defg'
s[::-1] # 'gfedcba' reversed
s[::2] # 'aceg' every 2nd2. Essential string methods
| Method | Effect | Example |
|---|---|---|
| split() | Split on whitespace | 'a b c'.split() β ['a','b','c'] |
| split(',') | Split on delimiter | 'a,b,c'.split(',') β ['a','b','c'] |
| join(iter) | Concatenate with separator | ','.join(['a','b']) β 'a,b' |
| strip() | Trim whitespace | ' hi '.strip() β 'hi' |
| replace(a, b) | Replace all | 'aaa'.replace('a','b') β 'bbb' |
| find(sub) | Index of first match (or -1) | 'hello'.find('ll') β 2 |
| count(sub) | Count occurrences | 'banana'.count('a') β 3 |
| isdigit() / isalpha() | Character class checks | '12'.isdigit() β True |
3. ASCII arithmetic
python
ord('A') # 65
ord('a') # 97
ord('0') # 48
chr(65) # 'A'
# Lowercase to uppercase
chr(ord('a') - 32) == 'A'
# 'c' - 'a' = letter index 0..25
ord('c') - ord('a') # 24. Two-pointer pattern (palindrome)
python
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return TrueExamples
Example 1 β src/01_slicing.py
Slicing demos: subranges, reversing, stepping.
Example 2 β src/02_string_methods.py
Daily-use methods: split/join/strip/replace/find.
Example 3 β src/03_palindrome.py
Two-pointer palindrome check, plus the one-liner with s == s[::-1].
Example 4 β src/04_anagram.py
Anagram check with collections.Counter β O(n).
Common Mistakes
- Treating strings as mutable. Strings are immutable β use list and ''.join() to build incrementally.
- Concatenating in a loop with `+=`. That's O(nΒ²). Use a list and join at the end.
- Off-by-one in s[:k] (exclusive) vs s[:k+1].
- Forgetting that .strip() returns a new string and doesn't modify in place.
Recap
- Slicing covers reversing, stepping, and substring extraction.
- Two-pointer is the workhorse pattern for string/array problems.
- Counter and ASCII arithmetic turn many problems into 2-line solutions.
Try It
- BOJ 10808 (Alphabet count).
- BOJ 1316 (Group word checker).
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β