ProgrammingHardAccenture · Cognizant pattern

What will be the output of the following pseudocode (counting pattern occurrences, allowing overlaps)?

What will be the output of the following pseudocode (counting pattern occurrences, allowing overlaps)?
Function countOcc(String text, String pat)
    Integer c = 0
    Integer n = length(text), m = length(pat)
    for (each i from 0 to n - m)
        if (substring(text, i, i + m) == pat)
            c = c + 1
        end if
    end for
    return c
End Function

Print countOcc("abababab", "aba")
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 1

Correct answer: C. 3

Checking every starting index, 'aba' matches at positions 0 ('abab...'->'aba'), 2 ('abab'->'aba'), and 4, giving 3 overlapping matches in 'abababab'.

More Pseudocode and Code Tracing questions

Exams that ask this topic