Data Structures & AlgorithmsVery hardLeetCode-style · GATE CS

A fence has 5 posts and each post is painted one of k = 3 colours. No three consecutive posts may share the same colour. How many colourings are possible?

  1. A. 186
  2. B. 180
  3. C. 243
  4. D. 66

Correct answer: B. 180

Track two states for each length: the number of valid colourings ending in a run of length 1 (diff) and in a run of length 2 (same). A new post either starts a new colour (k − 1 options from the previous colour) or extends a run of length 1; runs longer than 2 are forbidden.

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

Exams that ask this topic