DSA Notes
A thorough introduction to strings — what strings are, how they are stored in memory, immutability in Python and Java, all fundamental string operations with complexity, string comparison, slicing, building strings efficiently, and the most important string patterns for interviews.
What Is a String?
A string is a sequence of characters stored in a contiguous block of memory. It is one of the most fundamental data types in programming.
Under the hood, strings are arrays of characters — 'H', 'e', 'l', 'l', 'o' stored at consecutive memory addresses.
String Operations — Python
String Building — The O(n²) Trap
The trap: Concatenating strings in a loop is O(n²) in some languages.
# BAD — Python: O(n²) in theory (but CPython optimizes some cases)
result = ""
for i in range(10000):
result += str(i) # Each += creates a new string!
# GOOD — O(n): Build list, join once
parts = []
for i in range(10000):
parts.append(str(i))
result = ''.join(parts) # Single join callString Comparison
# Python string comparison — lexicographic, O(min(n,m))
print("apple" < "banana") # True — 'a' < 'b'
print("abc" < "abd") # True — first diff at index 2: 'c' < 'd'
print("abc" == "abc") # True — all chars equal
print("abc" < "abcd") # True — prefix is shorter
# Case-insensitive comparison
print("Hello".lower() == "hello".lower()) # True
# Compare by character value
print(ord('A')) # 65
print(ord('a')) # 97
print(ord('0')) # 48String Slicing in Python — O(k)
Key String Algorithms Preview
The following topics are covered in detail in subsequent lessons:
| Topic | Key Algorithm | Time |
|---|---|---|
| Pattern searching | KMP, Rabin-Karp | O(n+m) |
| Palindrome check | Two pointers | O(n) |
| Anagram check | Counter comparison | O(n) |
| String matching | Hash-based sliding window | O(n) |
| Longest common substring | DP table | O(n×m) |
Summary
- Strings are immutable sequences of characters in Python and Java
- O(1): length, index access
- O(n): search, case conversion, split, strip
- O(k): slicing (creates new string of length k)
- Never concatenate in a loop — use
''.join(list)in Python,StringBuilderin Java - String comparison is lexicographic — character by character
*Next Lesson: String Operations*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Strings — Complete Introduction to String Data Structure and Operations.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, strings, introduction, strings — complete introduction to string data structure and operations
Related Data Structures & Algorithms Topics