🎉 All 30 days are live — the full DSA-30 course, from Big-O to System Design. See the roadmap →

Basic Operations

Two candidates count the letters in a string. One reaches for a hash map; the other uses a plain 26-slot array and finishes faster with less memory. Same answer — but one knows a trick that the alphabet hands you for free. Most string “performance” in interviews comes down to knowing a few facts like this cold.

Every string operation you’ll encounter in interviews boils down to these fundamentals. Knowing their time complexities is the difference between an O(n) solution and an accidental O(n^2) one.

OperationTimeSpaceNotes
Access character by indexO(1)O(1)Direct offset calculation
Search for characterO(n)O(1)Linear scan
Search for substringO(n*m)O(1)Naive; O(n+m) with KMP
ConcatenationO(n+m)O(n+m)Creates new string (immutable languages)
Substring extractionO(k)O(k)k = length of substring
Compare two stringsO(n)O(1)Character-by-character
Reverse a stringO(n)O(1)In-place with two pointers (mutable)
Convert caseO(n)O(n)Must create new string (immutable)

Common Patterns to Remember

Predict first
You need to count how often each letter appears in a lowercase string. A hash map works — but what cheaper structure does the 'a–z' alphabet let you use instead, and how do you turn a character into an index?

The 26-array trick: When a problem involves only lowercase English letters, use int freq[26] (or [0]*26 in Python) indexed by char - 'a'. This is faster and more space-efficient than a hash map for character counting.

# Character frequency with the 26-array trick
def char_freq(s):
    freq = [0] * 26
    for ch in s.lower():
        if ch.isalpha():
            freq[ord(ch) - ord('a')] += 1
    return freq

Recall the index math

The whole trick is one line: turning a character into a slot 0–25. Fill it in from memory:

python · fill in the blanks0/1 hints
def char_freq(s):
freq = [0] * 26
for ch in s.lower():
if ch.isalpha():
# ??? map 'a'..'z' to slot 0..25 and bump it
return freq

Quick Check

What is the time complexity of checking if a string of length n contains a substring of length m using the naive approach?
In Java, what is wrong with comparing strings using == instead of .equals()?

These primitives (and the 26-array trick) are the building blocks for string algorithms — pattern matching, anagrams, and palindromes — which is where they combine into real interview solutions.

Finished this page?