Lesson 4 +25 XP

String Processing & Pattern Matching

String Processing & Pattern Matching

A String is a finite sequence of zero or more characters. In C, strings are stored as char arrays terminated by the null sentinel '\0' (ASCII 0).

1. String Storage Representations

  1. Fixed-Length Storage: Every string occupies a fixed buffer (e.g., char name[50]). Simple, but wastes memory on short strings and truncates long ones.
  2. Variable-Length with Sentinel / Length Field: C uses '\0' (requires O(n) scan for length); Pascal-style strings store length in byte 0 (O(1) length).
  3. Linked-Chunk Storage: Chains fixed-size character blocks with pointers-avoids large character shifts on mid-string insertions/deletions.

2. Core String Operations

  1. Length (strlen): Count characters until '\0' - O(n).
  2. Concatenation (strcat): Copy source characters starting at destination's '\0' - O(n + m).
  3. Comparison (strcmp): Compare ASCII values character-by-character until mismatch or '\0'.
  4. Substring Extraction: Copy len characters starting at pos.
  5. Insertion & Deletion: Shift trailing characters right (insert) or left (delete) - O(n).
C
int strLength(const char *s) {
    int len = 0;
    while (s[len] != '\0') len++;
    return len;
}

void strConcat(char *dest, const char *src) {
    int i = strLength(dest), j = 0;
    while ((dest[i++] = src[j++]) != '\0');
}

3. Pattern Matching Algorithms

Given a text T of length n and a pattern P of length m:

Naive Pattern Matching

Slide P over T one position at a time (i = 0 … n - m) and compare characters:

  • Best Case: O(n) (mismatch at first character each time).
  • Worst Case: O(n · m) (e.g., T = "AAAAAAB", P = "AAB").
C
int naiveSearch(const char *T, const char *P) {
    int n = strLength(T), m = strLength(P);
    for (int i = 0; i <= n - m; i++) {
        int j = 0;
        while (j < m && T[i + j] == P[j]) j++;
        if (j == m) return i;
    }
    return -1;
}

KMP (Knuth-Morris-Pratt) Algorithm

  • Precomputes an LPS (Longest Proper Prefix which is also Suffix) table of length m in O(m) time.
  • LPS Example: For P = &quot;ABABCABAB&quot;, LPS = [0, 0, 1, 2, 0, 1, 2, 3, 4].
  • On a mismatch at P[j], instead of resetting i backward in T, KMP sets j = lps[j - 1] and keeps moving i forward!
  • Total Time: O(n + m) worst-case.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain different String storage representations and write C functions for string length and concatenation without library functions. (5 Marks)
  • Write: Fixed-length, Variable-length ('\0' / length-prefixed), Linked-chunk; then write the while loop C functions for strLength and strConcat.
  • Q2. Explain Naive Pattern Matching vs KMP Pattern Matching with time complexity. (5 Marks)
  • Write: Naive O(n · m) sliding-window code + worst-case example (&quot;AAAAAAB&quot;, &quot;AAB&quot;), and KMP O(n + m) using the LPS table without backtracking T.