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 Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
POTD Solutions | 10 Nov’ 23 | Number following a pattern
Next article icon

POTD Solutions | 10 Nov’ 23 | Number following a pattern

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Stack and Two Pointer Algorithm but will also help you build up problem-solving skills.


10th-nov
POTD Solutions 10 November 2023


We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.
POTD 10th Nov
Number following a pattern
Solve!
Watch!

POTD 10 November: Number following a pattern

Given a pattern containing only I's and D's. I for increasing and D for decreasing. Devise an algorithm to print the minimum number following that pattern. Digits from 1-9 and digits can't repeat.

Examples: 

Input: D
Output: 21

Input: I
Output: 12

Input: DD
Output: 321

Number following a pattern using Stack:

We can that when we encounter I, we got numbers in increasing order but if we encounter ‘D’, we want to have numbers in decreasing order. Length of the output string is always one more than the input string. So the loop is from 0 to the length of the string. We have to take numbers from 1-9 so we always push (i+1) to our stack. Then we check what is the resulting character at the specified index.So, there will be two cases which are as follows:

Case 1: If we have encountered I or we are at the last character of input string, then pop from the stack and add it to the end of the output string until the stack gets empty. 

Case 2: If we have encountered D, then we want the numbers in decreasing order. so we just push (i+1) to our stack.

Below is the implmentation of the above approach:

C++
class Solution{    public:     string printMinNumberForPattern(string seq){            // result store output string      string result;         // create an empty stack of integers      stack<int> stk;         // run n+1 times where n is length of input sequence      for (int i = 0; i <= seq.length(); i++)      {          // push number i+1 into the stack          stk.push(i + 1);             // if all characters of the input sequence are          // processed or current character is 'I'          // (increasing)          if (i == seq.length() || seq[i] == 'I')          {              // run till stack is empty              while (!stk.empty())              {                  // remove top element from the stack and                  // add it to solution                  result += to_string(stk.top());                   stk.pop();              }          }      }         return result ;      } }; 
Java
class Solution{     static String printMinNumberForPattern(String seq){             // result store output string         StringBuilder result = new StringBuilder();          // create an empty stack of integers         Stack<Integer> stk = new Stack<>();          // run n+1 times where n is the length of the input sequence         for (int i = 0; i <= seq.length(); i++) {             // push number i+1 into the stack             stk.push(i + 1);              // if all characters of the input sequence are             // processed or the current character is 'I' (increasing)             if (i == seq.length() || seq.charAt(i) == 'I') {                 // run until the stack is empty                 while (!stk.isEmpty()) {                     // remove the top element from the stack and                     // add it to the solution                     result.append(stk.pop());                 }             }         }          return result.toString();     } } 
Python3
class Solution:     def printMinNumberForPattern(ob,seq):         # result stores the output string         result = []          # create an empty stack of integers         stk = []          # run n+1 times where n is the length of the input sequence         for i in range(len(seq) + 1):             # push number i+1 into the stack             stk.append(i + 1)              # if all characters of the input sequence are             # processed or the current character is 'I' (increasing)             if i == len(seq) or seq[i] == 'I':                 # run until the stack is empty                 while stk:                     # remove the top element from the stack and                     # add it to the solution                     result.append(str(stk.pop()))          return ''.join(result) 

Time Complexity: O(n) 
Auxiliary Space: O(n),  since n extra space has been taken.

Number following a pattern using Two Pointers:

  • Since we have to find a minimum number without repeating digits, maximum length of output can be 9 (using each 1-9 digits once)
  • Length of the output will be exactly one greater than input length.
  • The idea is to iterate over the string and do the following if current character is ‘I’ or string is ended. 
    • Assign count in increasing order to each element from current-1 to the next left index of ‘I’ (or starting index is reached).
    • Increase the count by 1.

Below is the implmentation of the above approach:

C++
class Solution{    public:     string printMinNumberForPattern(string seq){     int n = seq.length();         if (n >= 9)          return "-1";         string result(n+1, ' ');          int count = 1;           // The loop runs for each input character as well as       // one additional time for assigning rank to remaining characters      for (int i = 0; i <= n; i++)       {           if (i == n || seq[i] == 'I')          {              for (int j = i - 1 ; j >= -1 ; j--)              {                  result[j + 1] = '0' + count++;                  if(j >= 0 && seq[j] == 'I')                      break;              }          }      }      return result;      } }; 
Java
class Solution{     static String printMinNumberForPattern(String seq){       int n = seq.length();          if (n >= 9) {             return "-1";         }          char[] result = new char[n + 1];          int count = 1;          // The loop runs for each input character as well as         // one additional time for assigning rank to remaining characters         for (int i = 0; i <= n; i++) {             if (i == n || seq.charAt(i) == 'I') {                 for (int j = i - 1; j >= -1; j--) {                     result[j + 1] = (char) ('0' + count++);                     if (j >= 0 && seq.charAt(j) == 'I') {                         break;                     }                 }             }         }          return new String(result);     } } 
Python3
class Solution:     def printMinNumberForPattern(ob,seq):         # result stores the output string         n = len(seq)          if n >= 9:             return "-1"          result = [' '] * (n + 1)         count = 1          # The loop runs for each input character as well as         # one additional time for assigning rank to remaining characters         for i in range(n + 1):             if i == n or seq[i] == 'I':                 j = i - 1                 while j >= -1:                     result[j + 1] = str(count)                     count += 1                     if j >= 0 and seq[j] == 'I':                         break                     j -= 1          return ''.join(result) 

Time Complexity: O(N) 
Auxiliary Space: O(N), since N extra space has been taken.


POTD 10th Nov
Number following a pattern
Read Full Solution!

Next Article
POTD Solutions | 10 Nov’ 23 | Number following a pattern

V

vaibhav_gfg
Improve
Article Tags :
  • Competitive Programming
  • DSA
  • two-pointer-algorithm
Practice Tags :
  • two-pointer-algorithm

Similar Reads

    POTD Solutions | 09 Nov’ 23 | Predict the Column
    View all POTD SolutionsWelcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Matrix but will also help you build up problem-solving s
    4 min read
    GeeksforGeeks Problem Of The Day (POTD) Solutions | November 2023
    Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD) for the month of November 2023. We will discuss the entire problem step-by-step and work towards developing an optimized solution. Refer the detailed list of POTD solutions for the month of November 2023 below, along with its POTD probl
    2 min read
    CSES Solutions - Collecting Numbers
    You are given an array arr[] that contains each number between 1 ... N exactly once. Your task is to collect the numbers from 1 to N in increasing order. On each round, you go through the array from left to right and collect as many numbers as possible. What will be the total number of rounds? Examp
    6 min read
    GeeksforGeeks Problem Of The Day (POTD) Solutions | October 2023
    table{ display: inline-table !important; width: 100% !important; } Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD) for the month of October 2023. We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on
    3 min read
    GeeksforGeeks Problem Of The Day (POTD) Solutions | December 2023
    Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD) for the month of December 2023. We will discuss the entire problem step-by-step and work towards developing an optimized solution. Refer the detailed list of POTD solutions for the month of December 2023 below, along with its POTD probl
    2 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