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
  • Practice Searching Algorithms
  • MCQs on Searching Algorithms
  • Tutorial on Searching Algorithms
  • Linear Search
  • Binary Search
  • Ternary Search
  • Jump Search
  • Sentinel Linear Search
  • Interpolation Search
  • Exponential Search
  • Fibonacci Search
  • Ubiquitous Binary Search
  • Linear Search Vs Binary Search
  • Interpolation Search Vs Binary Search
  • Binary Search Vs Ternary Search
  • Sentinel Linear Search Vs Linear Search
Open In App
Next Article:
Count of Reverse Bitonic Substrings in a given String
Next article icon

Count of Reverse Bitonic Substrings in a given String

Last Updated : 07 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S, the task is to count the number of Reverse Bitonic Substrings in the given string.

Reverse bitonic substring: A string in which the ASCII values of the characters of the string follow any of the following patterns:

  • Strictly Increasing
  • Strictly decreasing
  • Decreasing and then increasing

Examples:

Input: S = "bade"
Output: 10
Explanation:  
All possible substrings of length 1, {"b", "a", "d”, "e"} are always reverse  bitonic. 
Substrings of length 2 which are reverse bitonic are {"ba", "ad", "de"}.
Substrings of length 3 which are reverse bitonic are {"bad ", "ade"}.
Only substring of length 4 which is reverse bitonic is "bade".
Therefore, the count of reverse bitonic substrings is 10.

Input: S = "abc"
Output: 6


Approach :
The approach is to generate all possible substrings of the given string and follow the steps below for each substring to solve the problem:

  • Traverse the string and for each character, check if the ASCII value of the next character is smaller than the ASCII value of the current character or not.
  • If at any point, the ASCII value of the next character is greater than the ASCII value of the current character, traverse from that index and for each character from now onwards, check if the ASCII value of the next character is greater than the ASCII value of the current character or not.
  • If at any point, the ASCII value of the next character is smaller than the ASCII value of the current character before the end of the substring is reached, then ignore the substring.
  • If the end of the substring is reached, increase count.
  • After completing all the above steps for all substrings, print the final value of count.

Below is the implementation of the above approach :

C++
// C++ Program to implement  // the above approach  #include <bits/stdc++.h>  using namespace std;   // Function to calculate the number  // of reverse bitonic substrings  int CountsubString(char str[], int n)  {      // Stores the count      int c = 0;       // All possible lengths of substrings      for (int len = 1; len <= n; len++) {           // Starting point of a substring          for (int i = 0; i <= n - len; i++) {               // Ending point of a substring              int j = i + len - 1;               char temp = str[i], f = 0;               // Condition for reverse              // bitonic substrings of              // length 1              if (j == i) {                   c++;                  continue;              }               int k = i + 1;               // Check for decreasing sequence              while (temp > str[k] && k <= j) {                   temp = str[k];                   k++;              }               // If end of substring              // is reached              if (k > j) {                  c++;                  f = 2;              }               // For increasing sequence              while (temp < str[k] && k <= j                  && f != 2) {                   temp = str[k];                   k++;              }               // If end of substring              // is reached              if (k > j && f != 2) {                  c++;                  f = 0;              }          }      }       // Return the number      // of bitonic substrings      return c;  }   // Driver Code  int main()  {      char str[] = "bade";      cout << CountsubString(str, strlen(str));       return 0;  } 
Java
// Java program to implement  // the above approach  class GFG{      // Function to calculate the number  // of reverse bitonic substrings  public static int CountsubString(char[] str,                                  int n)  {           // Stores the count      int c = 0;       // All possible lengths of substrings      for(int len = 1; len <= n; len++)     {                   // Starting point of a substring          for(int i = 0; i <= n - len; i++)         {                           // Ending point of a substring              int j = i + len - 1;               char temp = str[i], f = 0;               // Condition for reverse              // bitonic substrings of              // length 1              if (j == i)             {                  c++;                  continue;              }               int k = i + 1;               // Check for decreasing sequence              while (temp > str[k] && k <= j)             {                  temp = str[k];                  k++;              }               // If end of substring              // is reached              if (k > j)             {                  c++;                  f = 2;              }               // For increasing sequence              while (k <= j && temp < str[k] &&                    f != 2)              {                  temp = str[k];                  k++;              }               // If end of substring              // is reached              if (k > j && f != 2)             {                  c++;                  f = 0;              }          }      }       // Return the number      // of bitonic substrings      return c;  }   // Driver code public static void main(String[] args) {     char str[] = { 'b', 'a', 'd', 'e' };           System.out.println(CountsubString(                        str, str.length)); } }  // This code is contributed by divyeshrabadiya07 
Python3
# Python3 program to implement  # the above approach   # Function to calculate the number  # of reverse bitonic substrings  def CountsubString(strr, n):           # Stores the count      c = 0      # All possible lengths of substrings      for len in range(n + 1):           # Starting point of a substring          for i in range(n - len):               # Ending point of a substring              j = i + len - 1              temp = strr[i]              f = 0              # Condition for reverse              # bitonic substrings of              # length 1              if (j == i):                  c += 1                 continue              k = i + 1              # Check for decreasing sequence              while (k <= j and temp > strr[k]):                  temp = strr[k]                  k += 1              # If end of substring              # is reache              if (k > j):                  c += 1                 f = 2              # For increasing sequence              while (k <= j and f != 2 and                 temp < strr[k]):                  temp = strr[k]                  k += 1              # If end of substring              # is reached              if (k > j and f != 2):                  c += 1                 f = 0      # Return the number      # of bitonic substrings      return c   # Driver Code  if __name__ == '__main__':           strr = "bade"     print(CountsubString(strr, len(strr)))       # This code is contributed by mohit kumar 29  
C#
// C# program to implement  // the above approach  using System;  class GFG{      // Function to calculate the number  // of reverse bitonic substrings  public static int CountsubString(char[] str,                                  int n)  {           // Stores the count      int c = 0;       // All possible lengths of substrings      for(int len = 1; len <= n; len++)     {                 // Starting point of a substring          for(int i = 0; i <= n - len; i++)         {                           // Ending point of a substring              int j = i + len - 1;               char temp = str[i], f = '0';               // Condition for reverse              // bitonic substrings of              // length 1              if (j == i)             {                  c++;                  continue;              }               int k = i + 1;               // Check for decreasing sequence              while (temp > str[k] && k <= j)             {                  temp = str[k];                  k++;              }               // If end of substring              // is reached              if (k > j)             {                  c++;                  f = '2';              }               // For increasing sequence              while (k <= j && temp < str[k] &&                    f != '2')              {                  temp = str[k];                  k++;              }               // If end of substring              // is reached              if (k > j && f != 2)             {                  c++;                  f = '0';              }          }      }       // Return the number      // of bitonic substrings      return c;  }   // Driver code public static void Main(String[] args) {     char []str = { 'b', 'a', 'd', 'e' };           Console.WriteLine(CountsubString(                       str, str.Length) - 1); } }  // This code is contributed by amal kumar choubey 
JavaScript
<script>  // Javascript Program to implement  // the above approach   // Function to calculate the number  // of reverse bitonic substrings  function CountsubString(str, n)  {      // Stores the count      var c = 0;       // All possible lengths of substrings      for (var len = 1; len <= n; len++) {           // Starting point of a substring          for (var i = 0; i <= n - len; i++) {               // Ending point of a substring              var j = i + len - 1;               var temp = str[i], f = 0;               // Condition for reverse              // bitonic substrings of              // length 1              if (j == i) {                   c++;                  continue;              }               var k = i + 1;               // Check for decreasing sequence              while (temp > str[k] && k <= j) {                   temp = str[k];                   k++;              }               // If end of substring              // is reached              if (k > j) {                  c++;                  f = 2;              }               // For increasing sequence              while (temp < str[k] && k <= j                  && f != 2) {                   temp = str[k];                   k++;              }               // If end of substring              // is reached              if (k > j && f != 2) {                  c++;                  f = 0;              }          }      }       // Return the number      // of bitonic substrings      return c;  }   // Driver Code  var str = "bade".split('');  document.write( CountsubString(str, str.length));   // This code is contributed by importantly. </script>  

Output:

10

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


Next Article
Count of Reverse Bitonic Substrings in a given String

G

grand_master
Improve
Article Tags :
  • Strings
  • Searching
  • Competitive Programming
  • DSA
  • bitonic
  • substring
  • strings
Practice Tags :
  • Searching
  • Strings
  • Strings

Similar Reads

    Check if a given string is a Reverse Bitonic String or not
    Given a string str, the task is to check if that string is a Reverse Bitonic string or not. If the string str is reverse Bitonic string, then print "YES". Otherwise, print "NO". A Reverse Bitonic String is a string in which the characters are arranged in decreasing order followed by increasing order
    6 min read
    Count of bitonic substrings from the given string
    Given a string str, the task is to count all the bitonic substrings of the given string. A bitonic substring is a substring of the given string in which elements are either strictly increasing or strictly decreasing, or first increasing and then decreasing. Examples: Input: str = "bade"Output: 8Expl
    7 min read
    Count of increasing substrings in given String
    Given string str of length N, the task is to print the number of substrings in which every character's ASCII value is greater or equal to the ASCII value of the previous character. The substrings must at least be of length 2. Example: Input: str = "bcdabc"Output: 6Explanation: The 6 substrings with
    7 min read
    Count Palindromic Substrings in a Binary String
    Given a binary string S i.e. which consists only of 0's and 1's. Calculate the number of substrings of S which are palindromes. String S contains at most two 1's. Examples: Input: S = "011"Output: 4Explanation: "0", "1", "1" and "11" are the palindromic substrings. Input: S = "0" Output: 1Explanatio
    7 min read
    Count of substrings that start and end with 1 in given Binary String
    Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
    12 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