Data Structures & AlgorithmsHardGATE CS

The naive algorithm searches for P = "aaaab" in T = "aaabaaabaaaab": for each shift s = 0, 1, ..., it compares P[0], P[1], ... with T[s], T[s+1], ... and stops at the first mismatch or full match (it continues over all valid shifts). How many character comparisons are made in total?

  1. A. 45
  2. B. 28
  3. C. 25
  4. D. 21

Correct answer: C. 25

Counting comparisons shift by shift gives 25; the worst-case bound (number of shifts times |P|) would be 45, but mismatches stop most shifts early.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic