DSA/Lesson 2 of 11/5 min read
Arrays and Strings
Static and dynamic arrays, two pointers, sliding window, prefix sums, Kadane's algorithm and core string techniques.
On this page
Arrays
An array stores elements of the same type in contiguous memory. Address of element i is base + i * size, which makes random access O(1) and cache friendly.
| Operation | Complexity |
|---|---|
| Access by index | O(1) |
| Search (unsorted) | O(n) |
| Search (sorted, binary search) | O(log n) |
| Insert / delete at end | O(1) amortized |
| Insert / delete at middle | O(n) (shifting) |
Dynamic Array
A dynamic array grows by allocating a bigger block (usually 1.5x or 2x) and copying. Append is O(1) amortized. Examples: Python list, Java ArrayList, C++ vector.
Pitfall: holding a pointer or iterator into a C++ vector and then pushing can invalidate it after a reallocation.
2D arrays
Stored in row-major order in C, C++, Java and Python NumPy by default. Iterating row by row is much faster than column by column because of cache lines.
Two Pointers
Use two indices that move toward each other or in the same direction. Turns many O(n^2) pair searches into O(n).
Opposite ends: pair sum in a sorted array
def pair_sum(a, target):
l, r = 0, len(a) - 1
while l < r:
s = a[l] + a[r]
if s == target:
return l, r
if s < target:
l += 1
else:
r -= 1
return NoneSame direction: remove duplicates in place
def dedupe(a):
w = 0
for r in range(len(a)):
if r == 0 or a[r] != a[r - 1]:
a[w] = a[r]
w += 1
return wClassic problems: 3Sum, container with most water, Dutch national flag (three pointers), merging two sorted arrays.
Sliding Window
Maintain a window [l, r] over the array and update an aggregate as it slides. Each element enters and leaves once, so O(n).
Fixed size window
Max sum of any subarray of size k: add a[r], subtract a[r - k].
Variable size window
Longest substring without repeating characters:
def longest_unique(s):
seen = {}
l = best = 0
for r, ch in enumerate(s):
if ch in seen and seen[ch] >= l:
l = seen[ch] + 1
seen[ch] = r
best = max(best, r - l + 1)
return bestPattern: expand r; while the window is invalid, shrink l; record the answer.
Pitfall: sliding window on sums only works when all numbers are non-negative. With negatives, use prefix sums plus a hash map.
Prefix Sum
prefix[i] = sum of a[0..i-1]. Then the sum of a[l..r] is prefix[r + 1] - prefix[l] in O(1) after O(n) preprocessing.
prefix = [0]
for x in a:
prefix.append(prefix[-1] + x)Subarray sum equals k
Count subarrays with sum k (works with negatives): keep a hash map of how many times each prefix sum was seen; for each new prefix p, add count[p - k]. O(n) time.
Variants: 2D prefix sums for rectangle queries, difference arrays for range updates.
Kadane's Algorithm
Maximum subarray sum in O(n) time, O(1) space. At each index decide: extend the previous subarray or start fresh.
def max_subarray(a):
best = cur = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return bestThis is a tiny dynamic program: cur is the best sum ending at the current index.
Pitfall: initializing best = 0 gives the wrong answer when all numbers are negative.
Strings
A string is an array of characters. Know your language's encoding: ASCII is 1 byte, UTF-8 is variable length, so len in bytes and characters can differ.
String Immutability
In Java, Python, JavaScript and C#, strings are immutable. s += c in a loop creates a new string each time, which is O(n^2) total. Use a StringBuilder (Java) or collect into a list and "".join(parts) (Python).
Benefits of immutability: thread safety, safe to use as hash keys, string interning.
Palindrome
Reads the same forwards and backwards. Check with two pointers in O(n). Longest palindromic substring: expand around center for each of the 2n - 1 centers, O(n^2) time, O(1) space. Manacher's algorithm does it in O(n).
Anagram
Two strings with the same character counts. Compare frequency arrays of size 26 (O(n)) instead of sorting (O(n log n)). Group anagrams by using the sorted string or count tuple as a hash key.
Pattern matching
| Algorithm | Time | Idea |
|---|---|---|
| Naive | O(n * m) | Try every start |
| KMP | O(n + m) | LPS array avoids re-checking |
| Rabin-Karp | O(n + m) average | Rolling hash |
| Z-algorithm | O(n + m) | Z array of prefix matches |
Quick revision
- Arrays:
O(1)access,O(n)middle insert, contiguous and cache friendly. - Dynamic array append is
O(1)amortized because of doubling. - Two pointers turn pair searches on sorted data into
O(n). - Sliding window: expand right, shrink left while invalid; needs non-negative values for sum problems.
- Prefix sums give
O(1)range sums; pair with a hash map for subarray-sum-equals-k. - Kadane:
cur = max(x, cur + x). - Immutable strings make repeated concatenation
O(n^2); use a builder. - Anagram check: count array, not sort.