Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Generate Bitonic Sequence of length N from integers in a given range
Next article icon

Generate Bitonic Sequence of length N from integers in a given range

Last Updated : 22 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given integers N, L and R, the task is to generate a Bitonic Sequence of length N from the integers in the range [L, R] such that the first element is the maximum. If it is not possible to create such a sequence, then print "-1".

A Bitonic Sequence is a sequence that must be strictly increasing at first and then strictly decreasing.

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.

Input: N = 5, L = 2, R = 5
Output: 4, 5, 4, 3, 2
Explanation:
[ The sequence {4, 5, 4, 3, 2} is first strictly increasing and then strictly decreasing.

Approach: The idea is to use a Deque so that elements can be added from the end and the beginning. Follow the steps below to solve the problem:

  • Initialize a deque to store the element of the resultant bitonic sequence.
  • Initialize a variable i as 0 and start adding elements in the resultant list starting from (R - i) until i less than the minimum of (R - L + 1) and (N - 1).
  • After the above steps if the size of the resultant list is less than N then add elements from (R - 1) to L from the starting of the list until the size of the resultant list does not become N.
  • After the above steps, if N is greater than (R - L)*2 + 1, then it is not possible to construct such a sequence then print "-1" else print the sequence stored in deque.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to construct bitonic // sequence of length N from // integers in the range [L, R] void bitonicSequence(int num, int lower,                       int upper) {          // If sequence is not possible     if (num > (upper - lower) * 2 + 1)     {         cout << -1;         return;     }      // Store the resultant list     deque<int> ans;     deque<int>::iterator j = ans.begin();      for(int i = 0;             i < min(upper - lower + 1, num - 1);             i++)         ans.push_back(upper - i);              // If size of deque < n     for(int i = 0;             i < num - ans.size();              i++)               // Add elements from start     ans.push_front(upper - i - 1);      // Print the stored in the list     cout << '[';     for(j = ans.begin(); j != ans.end(); ++j)          cout << ' ' << *j;              cout << ' ' << ']';  }  // Driver Code int main() {     int N = 5, L = 3, R = 10;      // Function Call     bitonicSequence(N, L, R);      return 0; }  // This code is contributed by jana_sayantan 
Java
// Java program for the above approach import java.util.*;  class GFG {      // Function to construct bitonic     // sequence of length N from     // integers in the range [L, R]     public static void bitonicSequence(         int num, int lower, int upper)     {         // If sequence is not possible         if (num > (upper - lower) * 2 + 1) {             System.out.println(-1);             return;         }          // Store the resultant list         Deque<Integer> ans             = new ArrayDeque<>();          for (int i = 0;              i < Math.min(upper - lower + 1,                           num - 1);              i++)             ans.add(upper - i);          // If size of deque < n         for (int i = 0;              i < num - ans.size(); i++)              // Add elements from start             ans.addFirst(upper - i - 1);          // Print the stored in the list         System.out.println(ans);     }      // Driver Code     public static void main(String[] args)     {         int N = 5, L = 3, R = 10;          // Function Call         bitonicSequence(N, L, R);     } } 
Python3
# Python3 program for the above approach from collections import deque  # Function to construct bitonic # sequence of length N from # integers in the range [L, R] def bitonicSequence(num, lower, upper):          # If sequence is not possible     if (num > (upper - lower) * 2 + 1):         print(-1)         return      # Store the resultant list     ans = deque()          for i in range(min(upper - lower + 1,                                   num - 1)):         ans.append(upper - i)      # If size of deque < n     for i in range(num - len(ans)):                  # Add elements from start         ans.appendleft(upper - i - 1)      # Print the stored in the list     print(list(ans))  # Driver Code if __name__ == '__main__':          N = 5     L = 3     R = 10      # Function Call     bitonicSequence(N, L, R)  # This code is contributed by mohit kumar 29 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{  // Function to construct bitonic // sequence of length N from // integers in the range [L, R] public static void bitonicSequence(int num,                                     int lower,                                    int upper) {          // If sequence is not possible     if (num > (upper - lower) * 2 + 1)     {         Console.WriteLine(-1);         return;     }      // Store the resultant list     List<int> ans = new List<int>();      for(int i = 0;             i < Math.Min(upper - lower + 1,                            num - 1); i++)         ans.Add(upper - i);      // If size of deque < n     for(int i = 0;             i < num - ans.Count; i++)          // Add elements from start         ans.Insert(0,upper - i - 1);      // Print the stored in the list     Console.Write("[");     foreach(int x in ans)         Console.Write(x + ", ");              Console.Write("]"); }  // Driver Code public static void Main(String[] args) {     int N = 5, L = 3, R = 10;          // Function Call     bitonicSequence(N, L, R); } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>  // Javascript program for the above approach  // Function to construct bitonic // sequence of length N from // integers in the range [L, R] function bitonicSequence(num, lower, upper) {          // If sequence is not possible     if (num > (upper - lower) * 2 + 1)     {         document.write( -1);         return;     }      // Store the resultant list     var ans = [];      for(var i = 0;             i < Math.min(upper - lower + 1, num - 1);             i++)         ans.push(upper - i);              // If size of deque < n     for(var i = 0;             i < num - ans.length;              i++)     {                       // Add elements from start             ans.splice(0, 0, upper -i - 1)     }      // Print the stored in the list     document.write( '[');      ans.forEach(element => {         document.write(" "+element);     });              document.write( ' ' + ']');  }  // Driver Code var N = 5, L = 3, R = 10; // Function Call bitonicSequence(N, L, R);   </script>    

Output: 
[9, 10, 9, 8, 7]

 

Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Generate Bitonic Sequence of length N from integers in a given range

O

offbeat
Improve
Article Tags :
  • Greedy
  • Mathematical
  • DSA
  • Arrays
  • Amazon
  • interview-preparation
  • bitonic
  • deque
Practice Tags :
  • Amazon
  • Arrays
  • Deque
  • Greedy
  • Mathematical

Similar Reads

    Lexicographically largest N-length Bitonic sequence made up of elements from given range
    Given three integers N, low and high, the task is to find the lexicographically largest bitonic sequence consisting of N elements lying in the range [low, high]. If it is not possible to generate such a sequence, then print "Not Possible". Examples: Input: N = 5, low = 2, high = 6Output: 5 6 5 4 3Ex
    8 min read
    Find a sequence of distinct integers whose Harmonic Mean is N
    Given an integer N, the task is to find a sequence of distinct integers whose Harmonic Mean is N itself. In case such a sequence doesn't exist, print -1. Examples: Input: N = 5Output: {3, 4, 5, 6, 20} Explanation: Given sequence is the correct answer because 5/(1/3​+1/4+1/5​+1/6​+1/20)​=5. Note that
    6 min read
    Generate a N length Permutation having equal sized LIS from both ends
    Given an integer N, the task is to generate a permutation of elements in the range [1, N] in such order that the length of LIS from starting is equal to LIS from the end of the array. Print -1 if no such array exists. Examples: Input: N = 5Output: [1, 3, 5, 4, 2]Explanation:LIS from left side: [1, 3
    12 min read
    Maximum Length of Sequence of Sums of prime factors generated by the given operations
    Given two integers N and M, the task is to perform the following operations: For every value in the range [N, M], calculate the sum of its prime factors followed by the sum of prime factors of that sum and so on.Generate the above sequence for each array element and calculate the length of the seque
    12 min read
    Minimum number of coins that can generate all the values in the given range
    Given an integer N, the task is to find the minimum number of coins required to create all the values in the range [1, N]. Examples: Input: N = 5Output: 3The coins {1, 2, 4} can be used to generate all the values in the range [1, 5].1 = 12 = 23 = 1 + 24 = 45 = 1 + 4 Input: N = 10Output: 4 Approach:
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences