🚀 Phases 1–5 are live — Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap →

Basic Operations

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

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

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()?