Lesson 30 +30 XP

Array Techniques: Sliding Window, Two Pointers & Cyclic Sort (Beyond Syllabus)

Array Techniques: Sliding Window, Two Pointers & Cyclic Sort (Beyond Syllabus)

🧭 Beyond syllabus. These patterns are from the notes' practice list. They turn many O(n2) brute-force array solutions into O(n) ones and are the most common coding-interview patterns.

1. Sliding Window

Use it when the problem asks about a contiguous subarray or substring. Instead of recomputing each window from scratch, add the element entering the window and subtract the one leaving it.

Problem: maximum sum of any subarray of size k.

C
int maxSumWindow(int a[], int n, int k) {
    int sum = 0, best;
    for (int i = 0; i < k; i++) sum += a[i];      /* first window */
    best = sum;
    for (int i = k; i < n; i++) {
        sum += a[i] - a[i - k];                   /* slide by one */
        if (sum > best) best = sum;
    }
    return best;
}

Trace: a = [2, 1, 5, 1, 3, 2], k = 3

WindowSum
[2, 1, 5]8
[1, 5, 1]8 − 2 + 1 = 7
[5, 1, 3]7 − 1 + 3 = 9
[1, 3, 2]9 − 5 + 2 = 6

Maximum = 9, in O(n) instead of O(nk). A variable-size window (grow the right end, shrink the left end while a condition fails) solves &quot;longest substring without repeating characters&quot; and &quot;smallest subarray with sum ≥ S&quot;.

2. Two Pointers

Use two indices that move toward each other (or in the same direction) through a sorted array or a list.

Problem: in a sorted array, find a pair with sum = target.

C
int pairSum(int a[], int n, int target) {
    int i = 0, j = n - 1;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == target) { printf("%d + %d\n", a[i], a[j]); return 1; }
        if (s < target) i++;      /* need a bigger sum */
        else j--;                 /* need a smaller sum */
    }
    return 0;
}

For [1, 2, 3, 4, 6] and target 6: (1, 6) = 7 → j−−; (1, 4) = 5 → i++; (2, 4) = 6 ✓. O(n) instead of checking all O(n2) pairs.

Other two-pointer problems: remove duplicates from a sorted array in place, reverse an array, merge two sorted arrays (the merge step of merge sort), and the fast/slow pointers that detect a cycle in a linked list.

3. Cyclic Sort

Use it when the array holds numbers in a known range 1…n. Each number x belongs at index x − 1: keep swapping the current element into its correct place until the current position holds the right number (or a duplicate).

C
void cyclicSort(int a[], int n) {
    int i = 0;
    while (i < n) {
        int j = a[i] - 1;                      /* correct index of a[i] */
        if (a[i] != a[j]) { int t = a[i]; a[i] = a[j]; a[j] = t; }
        else i++;
    }
}

Every swap puts at least one number in its final place, so there are at most n swaps: O(n) time, O(1) extra space.

Finding the missing numbers: a = [4, 3, 2, 7, 8, 2, 3, 1] (n = 8, values 1…8). After cyclic sort: [1, 2, 3, 4, 3, 2, 7, 8]. Positions 5 and 6 do not hold 5 and 6, so the missing numbers are 5 and 6 (and the duplicates are 3 and 2).

4. Choosing a Pattern

Clue in the questionPattern
Contiguous subarray / substring, &quot;window of size k&quot;Sliding window
Sorted array, pair/triplet with a given sum, in-place removalTwo pointers
Numbers in range 1…n, find missing / duplicateCyclic sort
Linked list cycle or middle elementFast and slow pointers

📝 Practice Questions

  • Q1. Find the maximum sum of a subarray of size 3 in [2, 1, 5, 1, 3, 2] using the sliding-window technique.
  • Q2. Write a two-pointer algorithm to check whether a sorted array contains a pair with a given sum.
  • Q3. Use cyclic sort to find all missing numbers in [4, 3, 2, 7, 8, 2, 3, 1].