Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: How many pairs (i < j) of 'aabab' have s[i] = 'a' and s[j] = 'b'? Run the code.

Problem: How many pairs (i < j) of 'aabab' have s[i] = 'a' and s[j] = 'b'? Run the code.
s = 'aabab'
print(sum(1 for i in range(len(s)) for j in range(i + 1, len(s)) if s[i] == 'a' and s[j] == 'b'))
What is printed?
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: A. 5

The a positions are 0, 1, 3 and the b positions are 2, 4, giving the pairs (0,2), (0,4), (1,2), (1,4) and (3,4).

More Coding Interview Problems questions

Exams that ask this topic