Data Structures & AlgorithmsVery hard

Among all permutations of 1, 2, 3, 4 in which no two ADJACENT entries sum to 5, which one is lexicographically smallest? Give it as a space-separated sequence.

  1. A. 1 2 4 3
  2. B. 1 2 3 4
  3. C. 4 3 1 2
  4. D. 1 3 4 2

Correct answer: A. 1 2 4 3

Brute force over the 24 permutations: the lexicographic minimum is taken among only the valid ones. Ignoring the adjacency rule returns 1 2 3 4, the maximum is the last valid one, and the second valid permutation is not the smallest.

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

Exams that ask this topic