Data Structures & AlgorithmsModerateTCS NQT · Codeforces Div2 B

How many subarrays (i ≤ j) of [2, 1, 2, 3, 1, 2] have their first and last elements equal? A single element counts (its first and last are the same position).

  1. A. 4
  2. B. 11
  3. C. 21
  4. D. 10

Correct answer: D. 10

Count pairs of positions with equal values: each value v appearing c times contributes c(c+1)/2 subarrays including the single-element ones. Forgetting the single-element subarrays undercounts by n.

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

Exams that ask this topic