Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 02

Arrays & Strings Algorithms

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

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.

1

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.

Array: contiguous slots + index math

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() is O(1); pop(0) is O(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) time O(1) space (use k %= n).

Example

Code
Addressing 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)
2

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.

Two pointers walk from ends (or same direction)

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.

Example

Code
Pair 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 w
3

Sliding 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.

Sliding window: grow/shrink a range

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

Code
Fixed 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 best
4

Prefix 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.

Prefix sum: range sum in O(1)

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

  • Prefix array: P[i] = sum of first i elements.
  • Difference array: d[i]=a[i]-a[i-1]; supports O(1) range add.

Example

Code
Prefix 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 ans
5

Kadane'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.

Kadane: best subarray sum ending here

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

Code
Kadane 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

Example 01 · Basic

Row-major 2D array int A[10][20], base 1000, int size 4. Address of A[3][5]?

Given Data:
    Required To Find:

    Address

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Offset = (i*C + j) = 3*20 + 5 = 65 elements.
    Step 2: Bytes = 65*4 = 260.
    Step 3: Address = 1000 + 260.
    Final Answer: 1260

    Approach note: Column-major would be base + (j*R + i)*w = 1000 + (5*10+3)*4 = 1212.

    Example 02 · Intermediate

    Count subarrays of [1, 2, 3, -3, 3] with sum 3.

    Given Data:
      Required To Find:

      Count

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: cnt={0:1}. x=1: s=1, need -2 -> 0; cnt{1:1}.
      Step 2: x=2: s=3, need 0 -> 1 ([1,2]); cnt{3:1}.
      Step 3: x=3: s=6, need 3 -> 1 ([3]); cnt{6:1}.
      Step 4: x=-3: s=3, need 0 -> 1 ([1,2,3,-3]); cnt{3:2}.
      Step 5: x=3: s=6, need 3 -> 2 ([3,-3,3] and [3]); total 5.
      Final Answer: 5 subarrays

      Approach note: Always seed cnt[0]=1.

      Example 03 · Advanced

      Max sum circular subarray of [5, -3, 5].

      Given Data:
        Required To Find:

        Maximum sum

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Kadane max = 7 ([5,-3,5]) .
        Step 2: Min subarray = -3, total = 7.
        Step 3: Circular candidate = 7 - (-3) = 10 (wrap: 5 + 5).
        Step 4: Answer = max(7, 10).
        Final Answer: 10

        Approach note: If all elements are negative, return plain Kadane to avoid an empty wrap.

        Example 04 · Basic

        Array [2, 7, 11, 15], target 9. Return the two indices that sum to target (two-sum).

        Given Data:
          Required To Find:

          Index pair

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Scan left to right storing value→index
          Step 2: At 7, need 9-7=2 which was seen at index 0
          Step 3: Return [0, 1]
          Final Answer: [0, 1] (values 2 + 7 = 9)

          Approach note: One pass hash map is O(n) time and O(n) space.

          Real-world applications

          DSA

          Using Arrays & Strings Algorithms in real projects

          Time-series analytics (moving averages), text processing, range-sum queries, stock-profit problems.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          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

          1. Address row-major: base + (i*C + j)*w; column-major: base + (j*R + i)*w
          2. Two pointers: sorted + monotone rule, O(n) O(1)
          3. Window: add right, shrink left while invalid; negatives break it
          4. Prefix: sum(l..r)=P[r+1]-P[l]; seed count[0]=1
          5. Kadane: cur=max(x,cur+x); init with a[0]; circular = max(kadane, total-minSub)

          Practice questions

          Question 1 · MCQ (GATE)

          Column-major A[R][C], 0-indexed, base B, size w: address of A[i][j]?

          Question 2 · MCQ (Interview)

          Kadane on [-2,-3,-1,-5] returns:

          Question 3 · MCQ (Interview)

          Time to answer q range-sum queries on array of n using prefix sums:

          Question 4 · MCQ (Interview)

          Variable sliding window with inner while is:

          Question 5 · MCQ (Interview)

          Pair-sum two pointers requires the array to be: