VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-bitonic-sequence-of-length-n-from-integers-in-a-given-range/

⇱ Lexicographically Largest Bitonic Sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lexicographically Largest Bitonic Sequence

Last Updated : 30 Mar, 2026

Given integers n, l and r, generate a bitonic sequence of length n using integers from the range [l, r]. A bitonic sequence first strictly increases and then strictly decreases. There can be multiple possible sequences of the given length, you need to generate lexicographically largest sequence of al. If it is not possible to construct such a sequence, return [-1].

Note: n > 2.

Examples:

Input: n = 5, l = 3, r = 10
Output: 9, 10, 9, 8, 7
Explanation: The sequence {9, 10, 9, 8, 7} is first strictly increasing and then strictly decreasing. The other possible answers can be [7, 8, 9, 10, 9] or [8, 9, 10, 9, 8], but we need to choose the lexicographically largest one.

Input: n = 7, l = 2, r = 5
Output: 2, 3, 4, 5, 4, 3, 2
Explanation: The sequence {2, 3, 4, 5, 4, 3, 2} is first strictly increasing and then strictly decreasing.

Using Deque - O(n) Time and O(n) Space

The idea is to first insert r - 1, then place the maximum value r as the peak of the sequence. After that, add numbers from the range [l, r] in such a way that the sequence first increases and then decreases. A deque is used so that elements can be easily inserted at both the front and back while building the bitonic sequence.

Step by step approach:

  • Check if n > (r - l) * 2 + 1; if true, return [-1].
  • Initialize a deque and insert r - 1.
  • While the deque size is less than n, add decreasing elements from r to l at the tail.
  • If needed, add increasing elements from r - 2 to l at the head.
  • Convert the deque to an array and return the result.

Output
9 10 9 8 7 

Using Pre-calculation - O(n) Time and O(n) Space

The idea is to pre calculate how many numbers need to be added to the increasing and decreasing parts of the sequence, then build the sequence directly by placing the maximum value first, followed by carefully chosen values to fulfill the bitonic property.


Output
9 10 9 8 7 
Comment