Data Structures and Algorithms

Which is a characteristic of the Boyer-Moore algorithm for finding a pattern in a string?

  1. AIt compares the pattern starting from its last character and uses information such as the mismatched text character not appearing in the pattern to shift the pattern a long way at once
  2. BIt shifts the pattern one character at a time from the start of the text and compares every character of the pattern from first to last each time
  3. CIt sorts both the text and the pattern and then finds the pattern by binary search
Show answer and explanation

Answer: A. It compares the pattern starting from its last character and uses information such as the mismatched text character not appearing in the pattern to shift the pattern a long way at once

The Boyer-Moore algorithm compares the pattern from its last character and precomputes tables so that, for example, if the mismatched text character does not appear in the pattern at all, the whole pattern can be shifted past it. As a result, on natural-language text it can skip many characters without comparing them. With a text of length n and a pattern of length m, the naive method that shifts one character at a time and compares everything takes O(nm) in the worst case. The KMP algorithm also uses mismatch information to shift, but it compares from the start of the pattern and guarantees O(n + m) even in the worst case.

  • A. Correct. Comparing from the end and making large shifts based on the mismatched character is the Boyer-Moore algorithm.
  • B. This is the naive (brute-force) method, which takes O(nm) in the worst case.
  • C. The task is to find positions within the string, and sorting would destroy the position information.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. A dynamic array, when an element is added while it is full, allocates a new area with twice the capacity and copies all elements into it. If 1,000 elements are added one at a time to an empty array of capacity 1, how many element copies are made in total?
  2. For a hash table with many elements kept at a load factor of about 0.5, which is the most appropriate reason that open addressing with linear probing tends to be faster than chaining (linking elements with linked lists)?
  3. Sorting methods with a fixed sequence of compare-exchange steps (sorting networks), such as bitonic sort, are sometimes used for sorting on parallel hardware such as GPUs. Why?
  4. For an array of n elements, what is the time complexity of comparing every pair of distinct elements exactly once (a double loop that compares element i with every element after it, advancing i one step at a time)?
  5. A program with O(n²) time complexity takes 0.5 seconds for 1,000 data items. About how long will it take for 4,000 items?