Chapter 02
Arrays & Strings Algorithms
5 topics · 1 sections · beginner-friendly study notes · Updated
Arrays give O(1) random access through contiguous memory; most interview patterns on arrays and strings reduce O(n^2) brute force to O(n) using two pointers, sliding windows, prefix sums and Kadane-style dynamic programming.
Over a third of interview problems are array/string problems; these five tools solve most of them.
Time-series analytics (moving averages), text processing, range-sum queries, stock-profit problems.
Array Memory & Indexing
An array stores elements of equal size in contiguous memory. Address of A[i] = base + i*size (0-indexed). For a 2D array of R rows and C columns: row-major address = base + (i*C + j)*size; column-major = base + (j*R + i)*size.
In short: Elements sit side by side, so jumping to index i is one multiplication and one addition.
Think about it
Address-calculation questions appear almost every year in GATE; amortized resizing is a classic follow-up.
Access O(1); search unsorted O(n); insert/delete at position k shifts n-k elements: O(n) (O(1) at the end).
Dynamic arrays (Python list, Java ArrayList, C++ vector) double capacity when full: n appends cost O(n) total, so append is O(1) amortized, but a single append can cost O(n).
Arrays have excellent cache locality, making them faster in practice than linked lists even at equal Big-O. With lower bound LB (not 0), address = base + (i-LB)*size.
Strings are arrays of characters; in Python and Java they are immutable, so s[i]=c is illegal and repeated concatenation is O(n^2) - use a list and join, or StringBuilder.
Reading a 0-indexed array out of bounds is an error in Python/Java but undefined behaviour in C.
Key points
- Base address: Memory address of the first element.
- Row-major: Row elements contiguous (C, Java, NumPy default).
- Amortized
O(1): Average cost per op over many ops is constant even if some ops are expensive. - Cache locality: Contiguous access patterns hit CPU cache lines.
- Insert at index 0 of a Python list:
O(n).pop()isO(1);pop(0)isO(n)(use collections.deque). - Reverse in place: swap a[i] and a[n-1-i] for i < n/2,
O(n)time,O(1)space. - Rotate by k: reverse whole array, reverse first k, reverse rest,
O(n)timeO(1)space (use k%=n).
Example
CodeAddressing and rotation:
# Row-major address of A[i][j], base=B, elem size=w, C columns
def addr_row_major(B, i, j, C, w):
return B + (i * C + j) * w
# In-place rotate right by k
def rotate(a, k):
n = len(a); k %= n
def rev(l, r):
while l < r:
a[l], a[r] = a[r], a[l]; l += 1; r -= 1
rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)Two-Pointer Technique
Two indices move through a sequence under a rule: opposite ends moving inward (sorted array / palindrome), or a slow-fast pair moving in the same direction (partition, remove duplicates). Each pointer moves at most n times, giving O(n) total.
In short: Instead of checking all pairs, move two markers smartly so each element is visited once or twice.
Think about it
Cuts O(n^2) pair enumeration to O(n) with O(1) space; ubiquitous in interviews.
Pair sum on sorted array: if a[l]+a[r] < target move l right (need larger), if greater move r left.
Correct because discarding a[l] when sum is too small is safe: it cannot pair with any remaining element (all <= a[r]).
Requires sorted input, otherwise sort first (O(n log n)).
Three-sum: sort, fix i, two-pointer on the rest: O(n^2), skip duplicates to avoid repeated triplets.
Remove duplicates from sorted array: slow writes, fast reads, O(n)/O(1).
Dutch national flag (sort 0/1/2) uses three pointers lo, mid, hi in one pass.
Container with most water: move the shorter wall inward.
Edge cases: empty array, single element, all equal elements, no valid pair.
Key points
- Opposite-end pointers: l=0, r=n-1 moving toward each other.
- Slow/fast pointers: Both move forward at different rates or conditions.
- Invariant: Statement true throughout the loop that proves correctness.
Read more
Example
CodePair sum and de-duplication:
def pair_sum_sorted(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 None
def remove_duplicates(a): # sorted input, returns new length
if not a: return 0
w = 1
for r in range(1, len(a)):
if a[r] != a[w - 1]:
a[w] = a[r]; w += 1
return wSliding Window Pattern
A window [l, r] over a contiguous subarray/substring is moved forward by adding the new right element and removing the old left element, updating the aggregate in O(1) per step. Fixed-size windows have constant length k; variable windows expand r and shrink l to satisfy a condition.
In short: Slide a frame along the array, updating the answer by adding what enters and subtracting what leaves.
Think about it
Converts nested loops over subarrays into linear passes; very frequent in string problems.
Fixed window (max sum of k consecutive): O(n) vs O(nk) brute force.
Variable window template: for each r, add a[r]; while the window violates the constraint, remove a[l] and l++; then update the best answer.
Each element enters and leaves once, so O(n) even though there is a nested while.
Longest substring without repeating characters: keep a map char->last index, set l = max(l, last[c]+1): O(n).
Minimum window substring: maintain need/have counts.
Works for non-negative numbers when shrinking monotonically reduces the sum; with negative numbers the sum is not monotone so shrinking logic fails (use prefix sums + hash map instead).
Space O(1) for numeric windows, O(alphabet) for character windows.
Key points
- Window invariant: Condition the window must satisfy (e.g. all unique chars, sum
<=S). - Monotonicity: Expanding only helps one direction, shrinking the other; required for the shrink loop.
Example
CodeFixed and variable windows:
def max_sum_k(a, k): # fixed window
cur = sum(a[:k]); best = cur
for i in range(k, len(a)):
cur += a[i] - a[i - k]
best = max(best, cur)
return best
def longest_unique(s): # variable window
last = {}; l = best = 0
for r, c in enumerate(s):
if c in last and last[c] >= l:
l = last[c] + 1
last[c] = r
best = max(best, r - l + 1)
return best
def min_len_sum_ge(a, S): # positives only
l = tot = 0; best = float('inf')
for r, x in enumerate(a):
tot += x
while tot >= S:
best = min(best, r - l + 1)
tot -= a[l]; l += 1
return 0 if best == float('inf') else bestPrefix Sum Array
Prefix array P with P[0]=0 and P[i]=a[0]+...+a[i-1]. Sum of a[l..r] inclusive = P[r+1] - P[l], answered in O(1) after O(n) preprocessing. The 2D version uses inclusion-exclusion.
In short: Precompute running totals once, then any range sum is one subtraction.
Think about it
Turns repeated range queries from O(n) each to O(1) and enables counting subarrays with a hash map.
Subarray sum equals K (negatives allowed): iterate keeping running sum s and a hash map count of earlier prefix sums; the number of subarrays ending here = count[s-K].
Initialize count[0]=1 for subarrays starting at index 0.
O(n) time and O(n) space.
For divisible-by-K counting use prefix mod K. 2D prefix: P[i][j] = a + P[i-1][j] + P[i][j-1] - P[i-1][j-1]; query = P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1].
Difference array is the inverse trick: apply range add [l,r] += v as d[l]+=v, d[r+1]-=v, then prefix-sum to materialize: O(1) per update.
Overflow: in fixed-width languages sums can exceed int32; use 64-bit.
Prefix sums are for static arrays; with updates use Fenwick/segment tree.
Key points
Read more
Example
CodePrefix sums with hash map:
def build(a):
P = [0]
for x in a: P.append(P[-1] + x)
return P # sum(l..r) = P[r+1] - P[l]
def count_subarrays_sum_k(a, k):
cnt = {0: 1}; s = ans = 0
for x in a:
s += x
ans += cnt.get(s - k, 0)
cnt[s] = cnt.get(s, 0) + 1
return ansKadane's Algorithm
Maximum sum contiguous subarray in O(n): let cur = best sum of a subarray ending at i, cur = max(a[i], cur + a[i]); answer = max over i of cur. It is a 1-D dynamic programming recurrence with O(1) space.
In short: At each element, either extend the previous subarray or start fresh here, whichever is larger.
Think about it
Canonical example of optimal substructure turning quadratic into linear; asked in almost every interview loop.
Initialize cur = best = a[0] (NOT 0) so that an all-negative array returns the largest (least negative) element rather than 0 for an empty subarray.
If an empty subarray is allowed, initialize best = 0.
To recover indices track the start when cur resets to a[i].
Circular array variant: answer = max(kadane_max, total - kadane_min), except when all numbers are negative (then total - min = 0 means empty), return kadane_max.
Maximum product subarray needs both max and min ending here because a negative flips them.
Brute force is O(n^2) with prefix sums or O(n^3) naive.
Divide-and-conquer solution is O(n log n).
Stock buy-sell once is Kadane on differences.
Key points
- Subarray: Contiguous slice (a subsequence need not be contiguous).
- Optimal substructure: Best ending at i derived from best ending at i-1.
Example
CodeKadane variants:
def kadane(a):
cur = best = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
def kadane_with_indices(a):
cur = best = a[0]; s = bs = be = 0
for i in range(1, len(a)):
if a[i] > cur + a[i]:
cur = a[i]; s = i
else:
cur += a[i]
if cur > best:
best, bs, be = cur, s, i
return best, bs, be
def max_circular(a):
mx = kadane(a)
if mx < 0: return mx
mn = -kadane([-x for x in a])
return max(mx, sum(a) - mn)Solved examples
Row-major 2D array int A[10][20], base 1000, int size 4. Address of A[3][5]?
Address
Formula Applied:—Approach note: Column-major would be base + (j*R + i)*w = 1000 + (5*10+3)*4 = 1212.
Count subarrays of [1, 2, 3, -3, 3] with sum 3.
Count
Formula Applied:—Approach note: Always seed cnt[0]=1.
Max sum circular subarray of [5, -3, 5].
Maximum sum
Formula Applied:—Approach note: If all elements are negative, return plain Kadane to avoid an empty wrap.
Array [2, 7, 11, 15], target 9. Return the two indices that sum to target (two-sum).
Index pair
Formula Applied:—Approach note: One pass hash map is O(n) time and O(n) space.
Real-world applications
Using Arrays & Strings Algorithms in real projects
Time-series analytics (moving averages), text processing, range-sum queries, stock-profit problems.
Common mistakes
❌ Myth: Kadane works only when the array has a positive number.
Why this is wrong: Initializing with 0 fails for all-negative input, but initializing with a[0] works for all inputs.
✅ Verified Truth: cur = best = a[0] handles all-negative arrays correctly.
⚠️ Exam Tip: Test with [-3, -1, -2] -> answer -1.
❌ Myth: Sliding window works for subarray sum = K with negative numbers.
Why this is wrong: Negatives break monotonicity, so shrinking the window does not reliably decrease the sum.
✅ Verified Truth: Use prefix sums with a hash map for negatives.
⚠️ Exam Tip: Check constraints: all non-negative -> window; otherwise prefix map.
❌ Myth: Appending to a dynamic array is O(n).
Why this is wrong: Only occasional resize copies are O(n); doubling makes the average constant.
✅ Verified Truth: append is amortized O(1), worst single op O(n).
⚠️ Exam Tip: Quote "amortized" explicitly.
Revision notes
Arrays give O(1) random access through contiguous memory; most interview patterns on arrays and strings reduce O(n^2) brute force to O(n) using two pointers, sliding windows, prefix sums and Kadane-style dynamic programming.
High-Yield Quick Revision Points
- Address row-major: base + (i*C + j)*w; column-major: base + (j*R + i)*w
- Two pointers: sorted + monotone rule, O(n) O(1)
- Window: add right, shrink left while invalid; negatives break it
- Prefix: sum(l..r)=P[r+1]-P[l]; seed count[0]=1
- Kadane: cur=max(x,cur+x); init with a[0]; circular = max(kadane, total-minSub)
Practice questions
Column-major A[R][C], 0-indexed, base B, size w: address of A[i][j]?
Kadane on [-2,-3,-1,-5] returns:
Time to answer q range-sum queries on array of n using prefix sums:
Variable sliding window with inner while is:
Pair-sum two pointers requires the array to be: