VOOZH about

URL: https://www.geeksforgeeks.org/dsa/form-minimum-number-from-given-sequence/

⇱ Form minimum number from given sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Form minimum number from given sequence

Last Updated : 23 Jul, 2025

Auxiliary Given a pattern containing only I's and D's. I for increasing and D for decreasing. Device 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
 Input: II Output: 123
 Input: DIDI Output: 21435
 Input: IIDDD Output: 126543
 Input: DDIDDIID Output: 321654798

Source: Amazon Interview Question

We strongly recommend that you click here and practice it, before moving on to the solution.

Below are some important observations

Since digits can't repeat, there can be at most 9 digits in output. 

Also, number of digits in output is one more than number of characters in input. Note that the first character of input corresponds to two digits in output.

Idea is to iterate over input array and keep track of last printed digit and maximum digit printed so far. 

Steps were to follow to solve this problem:

  • Create a static function named "PrintMinNumberForPattern" that takes a string array arr as input.
  • Create two variables "curr_max" and "last_entry" and initialize them to 0.
  • Traverse through the input array arr using a for a loop.
  • Create a variable "noOfNextD" and initialize it to 0.
  • If the character at index i is 'I', perform the following steps:
    • Find the number of next consecutive D's available by iterating over the array from the next index until a non-'D'                                 character is encountered.
    •  If i is 0, set curr_max to noOfNextD+2 and print the incremented sequence from 1.
    • If i is not 0, set curr_max to curr_max + noOfNextD + 1 and print the digit for 'I'.
    •  For all next consecutive 'D' characters, print the decremented sequence.
  • If the character at index i is 'D', perform the following steps:
    •  If i is 0, find the number of the next consecutive 'D' characters available and set curr_max to noOfNextD+2. Print the first                        two digits (curr_max and curr_max-1).
    •  If i is not 0, print the decremented value of last_entry.
  • Print a newline character after the for loop completes.

Below is the implementation of the above idea:


Output
 1 3 2 5 4
 1 2
 3 2 1
 1 2 3
 2 1 4 3 5
 1 2 6 5 4 3
 3 2 1 6 5 4 7 9 8

Time Complexity: O(N^2), overall time complexity. Where, N is the length of the string.
Auxiliary Space: O(1).


This solution is suggested by Swapnil Trambake.

Alternate Solution: 
Let's observe a few facts in case of a minimum number: 

  • The digits can't repeat hence there can be 9 digits at most in output.
  • To form a minimum number , at every index of the output, we are interested in the minimum number which can be placed at that index.

The idea is to iterate over the entire input array , keeping track of the minimum number (1-9) which can be placed at that position of the output.

The tricky part of course occurs when 'D' is encountered at index other than 0. In such a case we have to track the nearest 'I' to the left of 'D' and increment each number in the output vector by 1 in between 'I' and 'D'. 
We cover the base case as follows: 

  • If the first character of input is 'I' then we append 1 and 2 in the output vector and the minimum available number is set to 3 .The index of most recent 'I' is set to 1.
  • If the first character of input is 'D' then we append 2 and 1 in the output vector and the minimum available number is set to 3, and the index of most recent 'I' is set to 0.

Now we iterate the input string from index 1 till its end and: 

  • If the character scanned is 'I' , a minimum value that has not been used yet is appended to the output vector .We increment the value of minimum no. available and index of most recent 'I' is also updated.
  • If the character scanned is 'D' at index i of input array, we append the ith element from output vector in the output and track the nearest 'I' to the left of 'D' and increment each number in the output vector by 1 in between 'I' and 'D'.

Following is the program for the same: 


Output
1 3 2 5 4 
1 2 
3 2 1 
1 2 3 
2 1 4 3 5 
1 2 6 5 4 3 
3 2 1 6 5 4 7 9 8 

Time Complexity: O(N2) ,here N is length of string .
Auxiliary Space: O(N)  since N extra space has been taken.

This solution is suggested by Ashutosh Kumar.
 
Method 3 
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.


Output
1 3 2 5 4 
1 2 
3 2 1 
1 2 3 
2 1 4 3 5 
1 2 6 5 4 3 
3 2 1 6 5 4 7 9 8 


Time Complexity: O(n) 
Auxiliary Space: O(n),  since n extra space has been taken.
This method is contributed by Roshni Agarwal

Method 4 (Using two pointers) 
Observation 

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

Input : I
Output : 12

Input : DD
Output : 321

Input : II
Output : 123

Input : DIDI
Output : 21435

Input : IIDDD
Output : 126543

Input : DDIDDIID
Output : 321654798

Below is the implementation of above approach:


Output
13254
12
321
123
21435
126543
321654798

Time Complexity: O(N) 
Auxiliary Space: O(N), since N extra space has been taken.
This solution is suggested by Brij Desai.

Method 5 (Start with the Smallest)

Start with the smallest number as the answer and keep shifting the digits when we encounter a D
There is no need to traverse back for the index.
Follow the below steps,

  1. Start with the smallest number for len(s)+1 (say for DI, start with "123")
  2. Now, starting with the second digit (index 1) and first character (D), iterate until end of the digits list, keeping track of the first D in a sequence of Ds
    1. When we encounter a D
      move the digit at current index to the first D in the sequence
    2. When we encounter an I
      reset the last known location of D. Nothing to move as the digit is correctly placed (as of now...)

Below is the implementation of the above approach:


Output
13254
12
321
123
21435
126543
321654798

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

Method 6 : (Space Optimized and modular code of Method 1)

Examples:

Input: "DDDD"
Output: "432156"

For input 1, pattern is like, D -> D -> D -> D
 5 4 3 2 1
 
Input: "DDDII"
Output: "432156"

For input 2, pattern is like, D -> D -> D -> I -> I
 4 3 2 1 5 6


Input: "IIDIDIII"
Output: "124365789"

For input 3, pattern is like, I -> I -> D -> I -> D -> I -> I -> I
 1 2 4 3 6 5 7 8 9 

Approach:

  • Think if the string contains only characters 'I' increasing, then there isn't any problem you can just print and keep incrementing.
  • Now think if the string contains only characters 'D' increasing, then you somehow have to get the number 'D' characters present from initial point, so that you can start from total count of 'D' and print by decrementing.
  • The problem is when you encounter character 'D' after character 'I'. Here somehow you have to get count of 'D' to get the next possible decremental start for 'D' and then print by decrementing until you have encountered all of 'D'.
  • Here in this approach the code has been made more modular compared to method 1 of space optimized version.

Output
214365
2143567
43215768
13254687
21354876
12438765

Time Complexity : O(n)

Auxiliary Space : O(1)

Method 7: (Substring Reversals)

The idea is to take the smallest number with len(s)+1 and perform reversals for every substring containing only 'D'.

Follow below steps to solve the problem:

1. Create the smallest possible number of length len(s)+1.

2. Traverse the string (say i).

3. Find the first and last occurrence of 'D' for every substring containing only 'D'.

4. Reverse every such substring and reinitialize first and last occurrence.


Output
321654798

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

Comment