Form minimum number from given sequence
Last Updated :
18 Sep, 2023
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
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:
C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include <bits/stdc++.h>
using namespace std;
// Prints the minimum number that can be formed from
// input sequence of I's and D's
void PrintMinNumberForPattern(string arr)
{
// Initialize current_max (to make sure that
// we don't use repeated character
int curr_max = 0;
// Initialize last_entry (Keeps track for
// last printed digit)
int last_entry = 0;
int j;
// Iterate over input array
for (int i=0; i<arr.length(); i++)
{
// Initialize 'noOfNextD' to get count of
// next D's available
int noOfNextD = 0;
switch(arr[i])
{
case 'I':
// If letter is 'I'
// Calculate number of next consecutive D's
// available
j = i+1;
while (arr[j] == 'D' && j < arr.length())
{
noOfNextD++;
j++;
}
if (i==0)
{
curr_max = noOfNextD + 2;
// If 'I' is first letter, print incremented
// sequence from 1
cout << " " << ++last_entry;
cout << " " << curr_max;
// Set max digit reached
last_entry = curr_max;
}
else
{
// If not first letter
// Get next digit to print
curr_max = curr_max + noOfNextD + 1;
// Print digit for I
last_entry = curr_max;
cout << " " << last_entry;
}
// For all next consecutive 'D' print
// decremented sequence
for (int k=0; k<noOfNextD; k++)
{
cout << " " << --last_entry;
i++;
}
break;
// If letter is 'D'
case 'D':
if (i == 0)
{
// If 'D' is first letter in sequence
// Find number of Next D's available
j = i+1;
while (arr[j] == 'D' && j < arr.length())
{
noOfNextD++;
j++;
}
// Calculate first digit to print based on
// number of consecutive D's
curr_max = noOfNextD + 2;
// Print twice for the first time
cout << " " << curr_max << " " << curr_max - 1;
// Store last entry
last_entry = curr_max - 1;
}
else
{
// If current 'D' is not first letter
// Decrement last_entry
cout << " " << last_entry - 1;
last_entry--;
}
break;
}
}
cout << endl;
}
// Driver program to test above
int main()
{
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
return 0;
}
Java
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
class GFG
{
// Prints the minimum number that can be formed from
// input sequence of I's and D's
static void PrintMinNumberForPattern(String arr)
{
// Initialize current_max (to make sure that
// we don't use repeated character
int curr_max = 0;
// Initialize last_entry (Keeps track for
// last printed digit)
int last_entry = 0;
int j;
// Iterate over input array
for (int i = 0; i < arr.length(); i++)
{
// Initialize 'noOfNextD' to get count of
// next D's available
int noOfNextD = 0;
switch (arr.charAt(i))
{
case 'I':
// If letter is 'I'
// Calculate number of next consecutive D's
// available
j = i + 1;
while (j < arr.length() && arr.charAt(j) == 'D')
{
noOfNextD++;
j++;
}
if (i == 0)
{
curr_max = noOfNextD + 2;
// If 'I' is first letter, print incremented
// sequence from 1
System.out.print(" " + ++last_entry);
System.out.print(" " + curr_max);
// Set max digit reached
last_entry = curr_max;
}
else
{
// If not first letter
// Get next digit to print
curr_max = curr_max + noOfNextD + 1;
// Print digit for I
last_entry = curr_max;
System.out.print(" " + last_entry);
}
// For all next consecutive 'D' print
// decremented sequence
for (int k = 0; k < noOfNextD; k++)
{
System.out.print(" " + --last_entry);
i++;
}
break;
// If letter is 'D'
case 'D':
if (i == 0)
{
// If 'D' is first letter in sequence
// Find number of Next D's available
j = i + 1;
while (j < arr.length()&&arr.charAt(j) == 'D')
{
noOfNextD++;
j++;
}
// Calculate first digit to print based on
// number of consecutive D's
curr_max = noOfNextD + 2;
// Print twice for the first time
System.out.print(" " + curr_max + " " + (curr_max - 1));
// Store last entry
last_entry = curr_max - 1;
}
else
{
// If current 'D' is not first letter
// Decrement last_entry
System.out.print(" " + (last_entry - 1));
last_entry--;
}
break;
}
}
System.out.println();
}
// Driver code
public static void main(String[] args)
{
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program to print minimum number that
# can be formed from a given sequence of Is and Ds
# Prints the minimum number that can be formed from
# input sequence of I's and D's
def PrintMinNumberForPattern(arr):
# Initialize current_max (to make sure that
# we don't use repeated character
curr_max = 0
# Initialize last_entry (Keeps track for
# last printed digit)
last_entry = 0
i = 0
# Iterate over input array
while i < len(arr):
# Initialize 'noOfNextD' to get count of
# next D's available
noOfNextD = 0
if arr[i] == "I":
# If letter is 'I'
# Calculate number of next consecutive D's
# available
j = i + 1
while j < len(arr) and arr[j] == "D":
noOfNextD += 1
j += 1
if i == 0:
curr_max = noOfNextD + 2
last_entry += 1
# If 'I' is first letter, print incremented
# sequence from 1
print("", last_entry, end = "")
print("", curr_max, end = "")
# Set max digit reached
last_entry = curr_max
else:
# If not first letter
# Get next digit to print
curr_max += noOfNextD + 1
# Print digit for I
last_entry = curr_max
print("", last_entry, end = "")
# For all next consecutive 'D' print
# decremented sequence
for k in range(noOfNextD):
last_entry -= 1
print("", last_entry, end = "")
i += 1
# If letter is 'D'
elif arr[i] == "D":
if i == 0:
# If 'D' is first letter in sequence
# Find number of Next D's available
j = i + 1
while j < len(arr) and arr[j] == "D":
noOfNextD += 1
j += 1
# Calculate first digit to print based on
# number of consecutive D's
curr_max = noOfNextD + 2
# Print twice for the first time
print("", curr_max, curr_max - 1, end = "")
# Store last entry
last_entry = curr_max - 1
else:
# If current 'D' is not first letter
# Decrement last_entry
print("", last_entry - 1, end = "")
last_entry -= 1
i += 1
print()
# Driver code
if __name__ == "__main__":
PrintMinNumberForPattern("IDID")
PrintMinNumberForPattern("I")
PrintMinNumberForPattern("DD")
PrintMinNumberForPattern("II")
PrintMinNumberForPattern("DIDI")
PrintMinNumberForPattern("IIDDD")
PrintMinNumberForPattern("DDIDDIID")
# This code is contributed by
# sanjeev2552
C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
class GFG
{
// Prints the minimum number that can be formed from
// input sequence of I's and D's
static void PrintMinNumberForPattern(String arr)
{
// Initialize current_max (to make sure that
// we don't use repeated character
int curr_max = 0;
// Initialize last_entry (Keeps track for
// last printed digit)
int last_entry = 0;
int j;
// Iterate over input array
for (int i = 0; i < arr.Length; i++)
{
// Initialize 'noOfNextD' to get count of
// next D's available
int noOfNextD = 0;
switch (arr[i])
{
case 'I':
// If letter is 'I'
// Calculate number of next consecutive D's
// available
j = i + 1;
while (j < arr.Length && arr[j] == 'D')
{
noOfNextD++;
j++;
}
if (i == 0)
{
curr_max = noOfNextD + 2;
// If 'I' is first letter, print incremented
// sequence from 1
Console.Write(" " + ++last_entry);
Console.Write(" " + curr_max);
// Set max digit reached
last_entry = curr_max;
}
else
{
// If not first letter
// Get next digit to print
curr_max = curr_max + noOfNextD + 1;
// Print digit for I
last_entry = curr_max;
Console.Write(" " + last_entry);
}
// For all next consecutive 'D' print
// decremented sequence
for (int k = 0; k < noOfNextD; k++)
{
Console.Write(" " + --last_entry);
i++;
}
break;
// If letter is 'D'
case 'D':
if (i == 0)
{
// If 'D' is first letter in sequence
// Find number of Next D's available
j = i + 1;
while (j < arr.Length&&arr[j] == 'D')
{
noOfNextD++;
j++;
}
// Calculate first digit to print based on
// number of consecutive D's
curr_max = noOfNextD + 2;
// Print twice for the first time
Console.Write(" " + curr_max + " " + (curr_max - 1));
// Store last entry
last_entry = curr_max - 1;
}
else
{
// If current 'D' is not first letter
// Decrement last_entry
Console.Write(" " + (last_entry - 1));
last_entry--;
}
break;
}
}
Console.WriteLine();
}
// Driver code
public static void Main(String[] args)
{
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
}
}
// This code is contributed by Princi Singh
PHP
<?php
// PHP program to print minimum
// number that can be formed
// from a given sequence of
// Is and Ds
// Prints the minimum number
// that can be formed from
// input sequence of I's and D's
function PrintMinNumberForPattern($arr)
{
// Initialize current_max
// (to make sure that
// we don't use repeated
// character
$curr_max = 0;
// Initialize last_entry
// (Keeps track for
// last printed digit)
$last_entry = 0;
$j;
// Iterate over
// input array
for ($i = 0; $i < strlen($arr); $i++)
{
// Initialize 'noOfNextD'
// to get count of
// next D's available
$noOfNextD = 0;
switch($arr[$i])
{
case 'I':
// If letter is 'I'
// Calculate number of
// next consecutive D's
// available
$j = $i + 1;
while ($arr[$j] == 'D' &&
$j < strlen($arr))
{
$noOfNextD++;
$j++;
}
if ($i == 0)
{
$curr_max = $noOfNextD + 2;
// If 'I' is first letter,
// print incremented
// sequence from 1
echo " " , ++$last_entry;
echo " " , $curr_max;
// Set max
// digit reached
$last_entry = $curr_max;
}
else
{
// If not first letter
// Get next digit
// to print
$curr_max = $curr_max +
$noOfNextD + 1;
// Print digit for I
$last_entry = $curr_max;
echo " " , $last_entry;
}
// For all next consecutive 'D'
// print decremented sequence
for ($k = 0; $k < $noOfNextD; $k++)
{
echo " " , --$last_entry;
$i++;
}
break;
// If letter is 'D'
case 'D':
if ($i == 0)
{
// If 'D' is first letter
// in sequence. Find number
// of Next D's available
$j = $i+1;
while (($arr[$j] == 'D') &&
($j < strlen($arr)))
{
$noOfNextD++;
$j++;
}
// Calculate first digit
// to print based on
// number of consecutive D's
$curr_max = $noOfNextD + 2;
// Print twice for
// the first time
echo " " , $curr_max ,
" " ,$curr_max - 1;
// Store last entry
$last_entry = $curr_max - 1;
}
else
{
// If current 'D'
// is not first letter
// Decrement last_entry
echo " " , $last_entry - 1;
$last_entry--;
}
break;
}
}
echo "\n";
}
// Driver Code
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
// This code is contributed by aj_36
?>
JavaScript
<script>
// Javascript program to print minimum number that can be formed
// from a given sequence of Is and Ds
// Prints the minimum number that can be formed from
// input sequence of I's and D's
function PrintMinNumberForPattern(arr)
{
// Initialize current_max (to make sure that
// we don't use repeated character
let curr_max = 0;
// Initialize last_entry (Keeps track for
// last printed digit)
let last_entry = 0;
let j;
// Iterate over input array
for (let i = 0; i < arr.length; i++)
{
// Initialize 'noOfNextD' to get count of
// next D's available
let noOfNextD = 0;
switch (arr[i])
{
case 'I':
// If letter is 'I'
// Calculate number of next consecutive D's
// available
j = i + 1;
while (j < arr.length && arr[j] == 'D')
{
noOfNextD++;
j++;
}
if (i == 0)
{
curr_max = noOfNextD + 2;
// If 'I' is first letter, print incremented
// sequence from 1
document.write(" " + ++last_entry);
document.write(" " + curr_max);
// Set max digit reached
last_entry = curr_max;
}
else
{
// If not first letter
// Get next digit to print
curr_max = curr_max + noOfNextD + 1;
// Print digit for I
last_entry = curr_max;
document.write(" " + last_entry);
}
// For all next consecutive 'D' print
// decremented sequence
for (let k = 0; k < noOfNextD; k++)
{
document.write(" " + --last_entry);
i++;
}
break;
// If letter is 'D'
case 'D':
if (i == 0)
{
// If 'D' is first letter in sequence
// Find number of Next D's available
j = i + 1;
while (j < arr.length && arr[j] == 'D')
{
noOfNextD++;
j++;
}
// Calculate first digit to print based on
// number of consecutive D's
curr_max = noOfNextD + 2;
// Print twice for the first time
document.write(" " + curr_max + " " + (curr_max - 1));
// Store last entry
last_entry = curr_max - 1;
}
else
{
// If current 'D' is not first letter
// Decrement last_entry
document.write(" " + (last_entry - 1));
last_entry--;
}
break;
}
}
document.write("<br>");
}
// Driver code
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
// This code is contributed by ab2127
</script>
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:
C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include<bits/stdc++.h>
using namespace std;
void printLeast(string arr)
{
// min_avail represents the minimum number which is
// still available for inserting in the output vector.
// pos_of_I keeps track of the most recent index
// where 'I' was encountered w.r.t the output vector
int min_avail = 1, pos_of_I = 0;
//vector to store the output
vector<int>v;
// cover the base cases
if (arr[0]=='I')
{
v.push_back(1);
v.push_back(2);
min_avail = 3;
pos_of_I = 1;
}
else
{
v.push_back(2);
v.push_back(1);
min_avail = 3;
pos_of_I = 0;
}
// Traverse rest of the input
for (int i=1; i<arr.length(); i++)
{
if (arr[i]=='I')
{
v.push_back(min_avail);
min_avail++;
pos_of_I = i+1;
}
else
{
v.push_back(v[i]);
for (int j=pos_of_I; j<=i; j++)
v[j]++;
min_avail++;
}
}
// print the number
for (int i=0; i<v.size(); i++)
cout << v[i] << " ";
cout << endl;
}
// Driver program to check the above function
int main()
{
printLeast("IDID");
printLeast("I");
printLeast("DD");
printLeast("II");
printLeast("DIDI");
printLeast("IIDDD");
printLeast("DDIDDIID");
return 0;
}
Java
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
import java.io.*;
import java.util.*;
public class GFG {
static void printLeast(String arr)
{
// min_avail represents the minimum number which is
// still available for inserting in the output vector.
// pos_of_I keeps track of the most recent index
// where 'I' was encountered w.r.t the output vector
int min_avail = 1, pos_of_I = 0;
//vector to store the output
ArrayList<Integer> al = new ArrayList<>();
// cover the base cases
if (arr.charAt(0) == 'I')
{
al.add(1);
al.add(2);
min_avail = 3;
pos_of_I = 1;
}
else
{
al.add(2);
al.add(1);
min_avail = 3;
pos_of_I = 0;
}
// Traverse rest of the input
for (int i = 1; i < arr.length(); i++)
{
if (arr.charAt(i) == 'I')
{
al.add(min_avail);
min_avail++;
pos_of_I = i + 1;
}
else
{
al.add(al.get(i));
for (int j = pos_of_I; j <= i; j++)
al.set(j, al.get(j) + 1);
min_avail++;
}
}
// print the number
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
System.out.println();
}
// Driver code
public static void main(String args[])
{
printLeast("IDID");
printLeast("I");
printLeast("DD");
printLeast("II");
printLeast("DIDI");
printLeast("IIDDD");
printLeast("DDIDDIID");
}
}
// This code is contributed by rachana soma
Python3
# Python3 program to print minimum number
# that can be formed from a given sequence
# of Is and Ds
def printLeast(arr):
# min_avail represents the minimum
# number which is still available
# for inserting in the output vector.
# pos_of_I keeps track of the most
# recent index where 'I' was
# encountered w.r.t the output vector
min_avail = 1
pos_of_I = 0
# Vector to store the output
v = []
# Cover the base cases
if (arr[0] == 'I'):
v.append(1)
v.append(2)
min_avail = 3
pos_of_I = 1
else:
v.append(2)
v.append(1)
min_avail = 3
pos_of_I = 0
# Traverse rest of the input
for i in range(1, len(arr)):
if (arr[i] == 'I'):
v.append(min_avail)
min_avail += 1
pos_of_I = i + 1
else:
v.append(v[i])
for j in range(pos_of_I, i + 1):
v[j] += 1
min_avail += 1
# Print the number
print(*v, sep = ' ')
# Driver code
printLeast("IDID")
printLeast("I")
printLeast("DD")
printLeast("II")
printLeast("DIDI")
printLeast("IIDDD")
printLeast("DDIDDIID")
# This code is contributed by avanitrachhadiya2155
C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections.Generic;
class GFG
{
static void printLeast(String arr)
{
// min_avail represents the minimum number which is
// still available for inserting in the output vector.
// pos_of_I keeps track of the most recent index
// where 'I' was encountered w.r.t the output vector
int min_avail = 1, pos_of_I = 0;
//vector to store the output
List<int> al = new List<int>();
// cover the base cases
if (arr[0] == 'I')
{
al.Add(1);
al.Add(2);
min_avail = 3;
pos_of_I = 1;
}
else
{
al.Add(2);
al.Add(1);
min_avail = 3;
pos_of_I = 0;
}
// Traverse rest of the input
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] == 'I')
{
al.Add(min_avail);
min_avail++;
pos_of_I = i + 1;
}
else
{
al.Add(al[i]);
for (int j = pos_of_I; j <= i; j++)
al[j] = al[j] + 1;
min_avail++;
}
}
// print the number
for (int i = 0; i < al.Count; i++)
Console.Write(al[i] + " ");
Console.WriteLine();
}
// Driver code
public static void Main(String []args)
{
printLeast("IDID");
printLeast("I");
printLeast("DD");
printLeast("II");
printLeast("DIDI");
printLeast("IIDDD");
printLeast("DDIDDIID");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to print
// minimum number that can be formed
// from a given sequence of Is and Ds
function printLeast(arr)
{
// min_avail represents the
// minimum number which is
// still available for inserting
// in the output vector.
// pos_of_I keeps track of the
// most recent index
// where 'I' was encountered
// w.r.t the output vector
let min_avail = 1, pos_of_I = 0;
//vector to store the output
let al = [];
// cover the base cases
if (arr[0] == 'I')
{
al.push(1);
al.push(2);
min_avail = 3;
pos_of_I = 1;
}
else
{
al.push(2);
al.push(1);
min_avail = 3;
pos_of_I = 0;
}
// Traverse rest of the input
for (let i = 1; i < arr.length; i++)
{
if (arr[i] == 'I')
{
al.push(min_avail);
min_avail++;
pos_of_I = i + 1;
}
else
{
al.push(al[i]);
for (let j = pos_of_I; j <= i; j++)
al[j] = al[j] + 1;
min_avail++;
}
}
// print the number
for (let i = 0; i < al.length; i++)
document.write(al[i] + " ");
document.write("</br>");
}
printLeast("IDID");
printLeast("I");
printLeast("DD");
printLeast("II");
printLeast("DIDI");
printLeast("IIDDD");
printLeast("DDIDDIID");
</script>
Output1 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.
C++
// C++ program to print minimum number that can be formed
// from a given sequence of Is and Ds
#include <bits/stdc++.h>
using namespace std;
// Function to decode the given sequence to construct
// minimum number without repeated digits
void 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());
result += " ";
stk.pop();
}
}
}
cout << result << endl;
}
// main function
int main()
{
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
return 0;
}
Java
import java.util.Stack;
// Java program to print minimum number that can be formed
// from a given sequence of Is and Ds
class GFG {
// Function to decode the given sequence to construct
// minimum number without repeated digits
static void PrintMinNumberForPattern(String seq) {
// result store output string
String result = "";
// create an empty stack of integers
Stack<Integer> stk = new Stack<Integer>();
// 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.charAt(i) == 'I') {
// run till stack is empty
while (!stk.empty()) {
// remove top element from the stack and
// add it to solution
result += String.valueOf(stk.peek());
result += " ";
stk.pop();
}
}
}
System.out.println(result);
}
// main function
public static void main(String[] args) {
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to print minimum
# number that can be formed from a
# given sequence of Is and Ds
def PrintMinNumberForPattern(Strr):
# Take a List to work as Stack
stack = []
# String for storing result
res = ''
# run n+1 times where n is length
# of input sequence, As length of
# result string is always 1 greater
for i in range(len(Strr) + 1):
# Push number i+1 into the stack
stack.append(i + 1)
# If all characters of the input
# sequence are processed or current
# character is 'I
if (i == len(Strr) or Strr[i] == 'I'):
# Run While Loop Until stack is empty
while len(stack) > 0:
# pop the element on top of stack
# And store it in result String
res += str(stack.pop())
res += ' '
# Print the result
print(res)
# Driver Code
PrintMinNumberForPattern("IDID")
PrintMinNumberForPattern("I")
PrintMinNumberForPattern("DD")
PrintMinNumberForPattern("II")
PrintMinNumberForPattern("DIDI")
PrintMinNumberForPattern("IIDDD")
PrintMinNumberForPattern("DDIDDIID")
# This code is contributed by AyushManglani
C#
// C# program to print minimum number that can be formed
// from a given sequence of Is and Ds
using System;
using System.Collections;
public class GFG {
// Function to decode the given sequence to construct
// minimum number without repeated digits
static void PrintMinNumberForPattern(String seq) {
// result store output string
String result = "";
// create an empty stack of integers
Stack stk = new Stack();
// 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.Count!=0) {
// remove top element from the stack and
// add it to solution
result += String.Join("",stk.Peek());
result += " ";
stk.Pop();
}
}
}
Console.WriteLine(result);
}
// main function
public static void Main() {
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to print
// minimum number that can be formed
// from a given sequence of Is and Ds
// Function to decode the given
// sequence to construct
// minimum number without repeated digits
function PrintMinNumberForPattern(seq)
{
// result store output string
let result = "";
// create an empty stack of integers
let stk = [];
// run n+1 times where n is length
// of input sequence
for (let 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.length!=0) {
// remove top element from
// the stack and
// add it to solution
result +=
(stk[stk.length - 1]).toString();
result += " ";
stk.pop();
}
}
}
document.write(result + "</br>");
}
PrintMinNumberForPattern("IDID");
PrintMinNumberForPattern("I");
PrintMinNumberForPattern("DD");
PrintMinNumberForPattern("II");
PrintMinNumberForPattern("DIDI");
PrintMinNumberForPattern("IIDDD");
PrintMinNumberForPattern("DDIDDIID");
</script>
Output1 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
- 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.
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:
C++
// C++ program of above approach
#include <bits/stdc++.h>
using namespace std;
// Returns minimum number made from given sequence without repeating digits
string getMinNumberForPattern(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;
}
// main function
int main()
{
string inputs[] = {"IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"};
for (string input : inputs)
{
cout << getMinNumberForPattern(input) << "\n";
}
return 0;
}
Java
// Java program of above approach
import java.io.IOException;
public class Test
{
// Returns minimum number made from given sequence without repeating digits
static String getMinNumberForPattern(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 each 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) ((int) '0' + count++);
if (j >= 0 && seq.charAt(j) == 'I')
break;
}
}
}
return new String(result);
}
public static void main(String[] args) throws IOException
{
String inputs[] = { "IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID" };
for(String input : inputs)
{
System.out.println(getMinNumberForPattern(input));
}
}
}
Python3
# Python3 program of above approach
# Returns minimum number made from
# given sequence without repeating digits
def getMinNumberForPattern(seq):
n = len(seq)
if (n >= 9):
return "-1"
result = [None] * (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'):
for j in range(i - 1, -2, -1):
result[j + 1] = int('0' + str(count))
count += 1
if(j >= 0 and seq[j] == 'I'):
break
return result
# Driver Code
if __name__ == '__main__':
inputs = ["IDID", "I", "DD", "II",
"DIDI", "IIDDD", "DDIDDIID"]
for Input in inputs:
print(*(getMinNumberForPattern(Input)))
# This code is contributed by PranchalK
C#
// C# program of above approach
using System;
class GFG
{
// Returns minimum number made from given
// sequence without repeating digits
static String getMinNumberForPattern(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 each 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] = (char) ((int) '0' + count++);
if (j >= 0 && seq[j] == 'I')
break;
}
}
}
return new String(result);
}
// Driver Code
public static void Main()
{
String []inputs = { "IDID", "I", "DD", "II",
"DIDI", "IIDDD", "DDIDDIID" };
foreach(String input in inputs)
{
Console.WriteLine(getMinNumberForPattern(input));
}
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program of above approach
// Returns minimum number made from given
// sequence without repeating digits
function getMinNumberForPattern(seq)
{
let n = seq.length;
if (n >= 9)
return "-1";
let result = new Array(n + 1);
let count = 1;
// The loop runs for each input character
// as well as one additional time for
// assigning rank to each remaining characters
for (let i = 0; i <= n; i++)
{
if (i == n || seq[i] == 'I')
{
for (let j = i - 1; j >= -1; j--)
{
result[j + 1] =
String.fromCharCode('0'.charCodeAt() +
count++);
if (j >= 0 && seq[j] == 'I')
break;
}
}
}
return result.join("");
}
let inputs = [ "IDID", "I", "DD", "II", "DIDI",
"IIDDD", "DDIDDIID" ];
for(let input = 0; input < inputs.length; input++)
{
document.write(
getMinNumberForPattern(inputs[input]) + "</br>"
);
}
</script>
Output13254
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,
- Start with the smallest number for len(s)+1 (say for DI, start with "123")
- 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
- When we encounter a D
move the digit at current index to the first D in the sequence - 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:
C++
// c++ program to generate required sequence
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
//:param s: a seq consisting only of 'D' and 'I' chars. D is
//for decreasing and I for increasing :return: digits from
//1-9 that fit the str. The number they represent should the min
//such number
vector<string> didi_seq_gen(string s)
{
if (s.size() == 0)
return {};
vector<string> base_list = { "1" };
for (int i = 2; i < s.size() + 2; i++)
base_list.push_back(to_string(i));
int last_D = -1;
for (int i = 1; i < base_list.size(); i++) {
if (s[i - 1] == 'D') {
if (last_D < 0)
last_D = i - 1;
string v = base_list[i];
base_list.erase(base_list.begin() + i);
base_list.insert(base_list.begin() + last_D, v);
}
else
last_D = -1;
}
return base_list;
}
int main()
{
vector<string> inputs
= { "IDID", "I", "DD", "II",
"DIDI", "IIDDD", "DDIDDIID" };
for (auto x : inputs) {
vector<string> ans = didi_seq_gen(x);
for (auto i : ans) {
cout << i;
}
cout << endl;
}
return 0;
}
Java
// Java program to generate required sequence
import java.util.*;
public class Main {
public static void main(String[] args)
{
String[] inputs
= { "IDID", "I", "DD", "II",
"DIDI", "IIDDD", "DDIDDIID" };
for (String x : inputs) {
List<String> ans = didi_seq_gen(x);
for (String i : ans) {
System.out.print(i);
}
System.out.println();
}
}
//:param s: a seq consisting only of 'D' and 'I' chars.
//D is for decreasing and I for increasing :return:
// digits from 1-9 that fit the str. The number they represent
// should the min such number
public static List<String> didi_seq_gen(String s)
{
if (s.length() == 0)
return new ArrayList<>();
List<String> base_list
= new ArrayList<>(Arrays.asList("1"));
for (int i = 2; i < s.length() + 2; i++)
base_list.add(Integer.toString(i));
int last_D = -1;
for (int i = 1; i < base_list.size(); i++) {
if (s.charAt(i - 1) == 'D') {
if (last_D < 0)
last_D = i - 1;
String v = base_list.get(i);
base_list.remove(i);
base_list.add(last_D, v);
}
else {
last_D = -1;
}
}
return base_list;
}
}
// This code is contributed by Tapesh (tapeshdua420)
Python3
# Python implementation of the above approach
def didi_seq_gen(s: str):
'''
:param s: a seq consisting only of 'D'
and 'I' chars. D is for decreasing and
I for increasing
:return: digits from 1-9 that fit the str.
The number they represent should the min
such number
:rtype: str
example : for seq DII -> 2134
'''
if not s or len(s) <= 0:
return ""
base_list = ["1"]
for i in range(1, len(s) + 1):
base_list.append(f'{i + 1}')
last_D = -1
for i in range(1, len(base_list)):
if s[i - 1] == 'D':
if last_D < 0:
last_D = i - 1
v = base_list[i]
del base_list[i]
base_list.insert(last_D, v)
else:
last_D = -1
return base_list
# Driver Code
# Function call
print(didi_seq_gen("IDID"))
print(didi_seq_gen("I"))
print(didi_seq_gen("DD"))
print(didi_seq_gen("II"))
print(didi_seq_gen("DIDI"))
print(didi_seq_gen("IIDDD"))
print(didi_seq_gen("DDIDDIID" ))
C#
// Include namespace system
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
public class GFG
{
public static void Main(String[] args)
{
String[] inputs = {"IDID", "I", "DD", "II", "DIDI", "IIDDD", "DDIDDIID"};
foreach (String x in inputs)
{
var ans = GFG.didi_seq_gen(x);
foreach (String i in ans)
{
Console.Write(i);
}
Console.WriteLine();
}
}
// :param s: a seq consisting only of 'D' and 'I' chars.
// D is for decreasing and I for increasing :return:
// digits from 1-9 that fit the str. The number they represent
// should the min such number
public static List<String> didi_seq_gen(String s)
{
if (s.Length == 0)
{
return new List<String>();
}
var base_list = new List<String>();
base_list.Add("1");
for (int i = 2; i < s.Length + 2; i++)
{
base_list.Add(Convert.ToString(i));
}
var last_D = -1;
for (int i = 1; i < base_list.Count; i++)
{
if (s[i - 1] == 'D')
{
if (last_D < 0)
{
last_D = i - 1;
}
var v = base_list[i];
base_list.RemoveAt(i);
base_list.Insert(last_D,v);
}
else
{
last_D = -1;
}
}
return base_list;
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// JavaScript implementation of the above approach
function didi_seq_gen(s)
{
if (!s || s.length <= 0)
return ""
let base_list = ["1"]
for (var i = 1; i <= s.length; i++)
base_list.push((i + 1).toString())
let last_D = -1
for (var i = 1; i < base_list.length; i++)
{
if (s[i - 1] == 'D')
{
if (last_D < 0)
last_D = i - 1
v = base_list[i]
base_list.splice(i, 1)
base_list.splice(last_D, 0, v)
}
else
last_D = -1
}
return base_list.join("")
}
// Driver Code
// Function call
console.log(didi_seq_gen("IDID"))
console.log(didi_seq_gen("I"))
console.log(didi_seq_gen("DD"))
console.log(didi_seq_gen("II"))
console.log(didi_seq_gen("DIDI"))
console.log(didi_seq_gen("IIDDD"))
console.log(didi_seq_gen("DDIDDIID" ))
// This code is contributed by poojaagarwal2.
Output13254
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.
C++
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
#include <bits/stdc++.h>
using namespace std;
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
string findMinNumberPattern(string str)
{
string ans = ""; // Minimum number following pattern
int i = 0;
int cur = 1; // cur val following pattern
int dCount = 0; // Count of char 'D'
while (i < str.length()) {
char ch = str[i];
// If 1st ch == 'I', incr and add to ans
if (i == 0 && ch == 'I') {
ans += to_string(cur);
cur++;
}
// If cur char == 'D',
// incr dCount as well, since we always
// start counting for dCount from i+1
if (ch == 'D') {
dCount++;
}
int j = i + 1; // Count 'D' from i+1 index
while (j < str.length()
&& str[j] == 'D') {
dCount++;
j++;
}
int k = dCount; // Store dCount
while (dCount >= 0) {
ans += to_string(cur + dCount);
dCount--;
}
cur += (k + 1); // Manages next cur val
dCount = 0;
i = j;
}
return ans;
}
int main()
{
cout << (findMinNumberPattern("DIDID")) << endl;
cout << (findMinNumberPattern("DIDIII")) << endl;
cout << (findMinNumberPattern("DDDIIDI")) << endl;
cout << (findMinNumberPattern("IDIDIID")) << endl;
cout << (findMinNumberPattern("DIIDIDD")) << endl;
cout << (findMinNumberPattern("IIDIDDD")) << endl;
return 0;
}
// This code is contributed by suresh07.
Java
/*package whatever //do not write package name here */
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
import java.io.*;
class GFG {
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
public static String findMinNumberPattern(String str)
{
String ans = ""; // Minimum number following pattern
int i = 0;
int cur = 1; // cur val following pattern
int dCount = 0; // Count of char 'D'
while (i < str.length()) {
char ch = str.charAt(i);
// If 1st ch == 'I', incr and add to ans
if (i == 0 && ch == 'I') {
ans += cur;
cur++;
}
// If cur char == 'D',
// incr dCount as well, since we always
// start counting for dCount from i+1
if (ch == 'D') {
dCount++;
}
int j = i + 1; // Count 'D' from i+1 index
while (j < str.length()
&& str.charAt(j) == 'D') {
dCount++;
j++;
}
int k = dCount; // Store dCount
while (dCount >= 0) {
ans += (cur + dCount);
dCount--;
}
cur += (k + 1); // Manages next cur val
dCount = 0;
i = j;
}
return ans;
}
public static void main(String[] args)
{
System.out.println(findMinNumberPattern("DIDID"));
System.out.println(findMinNumberPattern("DIDIII"));
System.out.println(findMinNumberPattern("DDDIIDI"));
System.out.println(findMinNumberPattern("IDIDIID"));
System.out.println(findMinNumberPattern("DIIDIDD"));
System.out.println(findMinNumberPattern("IIDIDDD"));
}
}
// This code is contributed by Arun M
Python3
# This code illustrates to find minimum number following
# pattern with optimized space and modular code.
# This function returns minimum number following
# pattern of increasing or decreasing sequence.
def findMinNumberPattern(Str):
ans = "" # Minimum number following pattern
i = 0
cur = 1 # cur val following pattern
dCount = 0 # Count of char 'D'
while (i < len(Str)) :
ch = Str[i]
# If 1st ch == 'I', incr and add to ans
if (i == 0 and ch == 'I') :
ans += str(cur)
cur+=1
# If cur char == 'D',
# incr dCount as well, since we always
# start counting for dCount from i+1
if (ch == 'D') :
dCount+=1
j = i + 1 # Count 'D' from i+1 index
while (j < len(Str) and Str[j] == 'D') :
dCount+=1
j+=1
k = dCount # Store dCount
while (dCount >= 0) :
ans += str(cur + dCount)
dCount-=1
cur += (k + 1) # Manages next cur val
dCount = 0
i = j
return ans
print(findMinNumberPattern("DIDID"))
print(findMinNumberPattern("DIDIII"))
print(findMinNumberPattern("DDDIIDI"))
print(findMinNumberPattern("IDIDIID"))
print(findMinNumberPattern("DIIDIDD"))
print(findMinNumberPattern("IIDIDDD"))
# This code is contributed by mukesh07.
C#
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
using System;
class GFG {
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
public static string findMinNumberPattern(string str)
{
string ans = ""; // Minimum number following pattern
int i = 0;
int cur = 1; // cur val following pattern
int dCount = 0; // Count of char 'D'
while (i < str.Length) {
char ch = str[i];
// If 1st ch == 'I', incr and add to ans
if (i == 0 && ch == 'I') {
ans += cur;
cur++;
}
// If cur char == 'D',
// incr dCount as well, since we always
// start counting for dCount from i+1
if (ch == 'D') {
dCount++;
}
int j = i + 1; // Count 'D' from i+1 index
while (j < str.Length
&& str[j] == 'D') {
dCount++;
j++;
}
int k = dCount; // Store dCount
while (dCount >= 0) {
ans += (cur + dCount);
dCount--;
}
cur += (k + 1); // Manages next cur val
dCount = 0;
i = j;
}
return ans;
}
static void Main() {
Console.WriteLine(findMinNumberPattern("DIDID"));
Console.WriteLine(findMinNumberPattern("DIDIII"));
Console.WriteLine(findMinNumberPattern("DDDIIDI"));
Console.WriteLine(findMinNumberPattern("IDIDIID"));
Console.WriteLine(findMinNumberPattern("DIIDIDD"));
Console.WriteLine(findMinNumberPattern("IIDIDDD"));
}
}
// This code is contributed by mukesh07.
JavaScript
<script>
// This code illustrates to find minimum number following
// pattern with optimized space and modular code.
// This function returns minimum number following
// pattern of increasing or decreasing sequence.
function findMinNumberPattern(str)
{
let ans = ""; // Minimum number following pattern
let i = 0;
let cur = 1; // cur val following pattern
let dCount = 0; // Count of char 'D'
while (i < str.length) {
let ch = str[i];
// If 1st ch == 'I', incr and add to ans
if (i == 0 && ch == 'I') {
ans += cur;
cur++;
}
// If cur char == 'D',
// incr dCount as well, since we always
// start counting for dCount from i+1
if (ch == 'D') {
dCount++;
}
let j = i + 1; // Count 'D' from i+1 index
while (j < str.length
&& str[j] == 'D') {
dCount++;
j++;
}
let k = dCount; // Store dCount
while (dCount >= 0) {
ans += (cur + dCount);
dCount--;
}
cur += (k + 1); // Manages next cur val
dCount = 0;
i = j;
}
return ans;
}
document.write(findMinNumberPattern("DIDID")+"<br>");
document.write(findMinNumberPattern("DIDIII")+"<br>");
document.write(findMinNumberPattern("DDDIIDI")+"<br>");
document.write(findMinNumberPattern("IDIDIID")+"<br>");
document.write(findMinNumberPattern("DIIDIDD")+"<br>");
document.write(findMinNumberPattern("IIDIDDD")+"<br>");
// This code is contributed by unknown2108
</script>
Output214365
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.
C++14
#include <bits/stdc++.h>
using namespace std;
string get_num_seq(string& str_seq)
{
int n=str_seq.length(),start=-1,end=-1;
string ans;
for(int i=1;i<=n+1;i++)
ans.push_back(i+48);
for(int i=0;i<n;i++)
{
if(str_seq[i]=='D')
{
if(start==-1)
start=i;
end=i;
}
else {
if(start!=-1)
reverse(ans.begin()+start,ans.begin()+end+2);
start=-1;
end=-1;
}
}
if(start!=-1)
reverse(ans.begin()+start,ans.begin()+end+2);
return ans;
}
// driver's code
int main()
{
string str_seq="DDIDDIID";
cout<<get_num_seq(str_seq);
return 0;
}
// this code is contributed by prophet1999
Java
// Java code for the above approach
import java.io.*;
class GFG {
public static String getNumSeq(String strSeq)
{
int n = strSeq.length();
int start = -1;
int end = -1;
String ans = "";
for (int i = 1; i <= n + 1; i++) {
ans += String.valueOf(i);
}
for (int i = 0; i < n; i++) {
if (strSeq.charAt(i) == 'D') {
if (start == -1) {
start = i;
}
end = i;
}
else {
if (start != -1) {
ans = reverse(ans, start, end + 2);
}
start = -1;
end = -1;
}
}
if (start != -1) {
ans = reverse(ans, start, end + 2);
}
return ans;
}
public static String reverse(String str, int start,
int end)
{
char[] arr = str.toCharArray();
for (int i = start, j = end - 1; i < j; i++, j--) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return new String(arr);
}
public static void main(String[] args)
{
String strSeq = "DDIDDIID";
System.out.println(getNumSeq(strSeq));
}
}
// This code is contributed by lokesh.
Python3
def get_num_seq( str_seq):
n= len(str_seq)
start = -1
end = -1;
ans = "";
for i in range(1, n + 2):
ans += str(i)
for i in range(n):
if(str_seq[i] == 'D'):
if(start == -1):
start=i;
end=i;
else:
if(start != -1):
ans = ans[:start] + ans[start:end+2][::-1] + ans[end+2:]
start = -1;
end = -1;
if(start != -1):
ans = ans[:start] + ans[start:end+2][::-1] + ans[end+2:]
return ans;
# driver's code
str_seq="DDIDDIID";
print(get_num_seq(str_seq))
# this code is contributed by phasing17
C#
// C# code for the above approach
using System;
public class GFG {
public static string GetNumSeq(string strSeq)
{
int n = strSeq.Length;
int start = -1;
int end = -1;
string ans = "";
for (int i = 1; i <= n + 1; i++) {
ans += i.ToString();
}
for (int i = 0; i < n; i++) {
if (strSeq[i] == 'D') {
if (start == -1) {
start = i;
}
end = i;
}
else {
if (start != -1) {
ans = Reverse(ans, start, end + 2);
}
start = -1;
end = -1;
}
}
if (start != -1) {
ans = Reverse(ans, start, end + 2);
}
return ans;
}
public static string Reverse(string str, int start,
int end)
{
char[] arr = str.ToCharArray();
for (int i = start, j = end - 1; i < j; i++, j--) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return new string(arr);
}
static public void Main()
{
// Code
string strSeq = "DDIDDIID";
Console.WriteLine(GetNumSeq(strSeq));
}
}
// This code is contributed by lokeshmvs21.
JavaScript
function get_num_seq(strSeq) {
let n = strSeq.length;
let start = -1;
let end = -1;
let ans = "";
for (let i = 1; i <= n + 1; i++) {
ans += String.fromCharCode(i+48);
}
for (let i = 0; i < n; i++) {
if (strSeq[i] === 'D') {
if (start === -1) {
start = i;
}
end = i;
} else {
if (start !== -1) {
ans = ans.slice(0, start) + ans.slice(start, end + 2).split("").reverse().join("") + ans.slice(end + 2);
}
start = -1;
end = -1;
}
}
if (start !== -1) {
ans = ans.slice(0, start) + ans.slice(start, end + 2).split("").reverse().join("") + ans.slice(end + 2);
}
return ans;
}
//driver's code
let str_seq="DDIDDIID";
document.write(get_num_seq(str_seq));
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
String in Data Structure
A string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
3 min read
Introduction to Strings - Data Structure and Algorithm Tutorials
Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character â\0â and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings:"geeks"
7 min read
Applications, Advantages and Disadvantages of String
The String data structure is the backbone of programming languages and the building blocks of communication. String data structures are one of the most fundamental and widely used tools in computer science and programming. They allow for the representation and manipulation of text and character sequ
6 min read
Subsequence and Substring
What is a Substring? A substring is a contiguous part of a string, i.e., a string inside another string. In general, for an string of size n, there are n*(n+1)/2 non-empty substrings. For example, Consider the string "geeks", There are 15 non-empty substrings. The subarrays are: g, ge, gee, geek, ge
6 min read
Storage for Strings in C
In C, a string can be referred to either using a character pointer or as a character array. Strings as character arrays C char str[4] = "GfG"; /*One extra for string terminator*/ /* OR */ char str[4] = {âGâ, âfâ, âGâ, '\0'}; /* '\0' is string terminator */ When strings are declared as character arra
5 min read
Strings in different language
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is work as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'.DeclarationDeclaring a string in C i
5 min read
std::string class in C++
C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. The string class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.String vs Character ArrayStringChar
8 min read
String Class in Java
A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl
7 min read
Python String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
C# Strings
In C#, a string is a sequence of Unicode characters or an array of characters. The range of Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed as the text. So the string is the representation of the text. A string is an important concept, and sometimes people get con
7 min read
JavaScript String Methods
JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
11 min read
PHP Strings
In PHP, strings are one of the most commonly used data types. A string is a sequence of characters used to represent text, such as words and sentences. Strings are enclosed in either single quotes (' ') or double quotes (" "). You can create a string using single quotes (' ') or double quotes (" ").
4 min read
Basic operations on String
Searching For Characters and Substring in a String in Java
Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.Searching for a Character in a
5 min read
Reverse a String â Complete Tutorial
Given a string s, the task is to reverse the string. Reversing a string means rearranging the characters such that the first character becomes the last, the second character becomes second last and so on.Examples:Input: s = "GeeksforGeeks"Output: "skeeGrofskeeG"Explanation : The first character G mo
13 min read
Left Rotation of a String
Given a string s and an integer d, the task is to left rotate the string by d positions.Examples:Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe".Input: s = "qwer
15+ min read
Sort string of characters
Given a string of lowercase characters from 'a' - 'z'. We need to write a program to print the characters of this string in sorted order.Examples: Input : "dcab" Output : "abcd"Input : "geeksforgeeks"Output : "eeeefggkkorss"Naive Approach - O(n Log n) TimeA simple approach is to use sorting algorith
5 min read
Frequency of Characters in Alphabetical Order
Given a string s, the task is to print the frequency of each of the characters of s in alphabetical order.Example: Input: s = "aabccccddd" Output: a2b1c4d3 Since it is already in alphabetical order, the frequency of the characters is returned for each character. Input: s = "geeksforgeeks" Output: e4
9 min read
Swap characters in a String
Given a String S of length N, two integers B and C, the task is to traverse characters starting from the beginning, swapping a character with the character after C places from it, i.e. swap characters at position i and (i + C)%N. Repeat this process B times, advancing one position at a time. Your ta
14 min read
C Program to Find the Length of a String
The length of a string is the number of characters in it without including the null character (â\0â). In this article, we will learn how to find the length of a string in C.The easiest way to find the string length is by using strlen() function from the C strings library. Let's take a look at an exa
2 min read
How to insert characters in a string at a certain position?
Given a string str and an array of indices chars[] that describes the indices in the original string where the characters will be added. For this post, let the character to be inserted in star (*). Each star should be inserted before the character at the given index. Return the modified string after
7 min read
Check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Consider case sensitivity.Examples:Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Approach - By Using (==) in C++/Python/C#, eq
7 min read
Concatenating Two Strings in C
Concatenating two strings means appending one string at the end of another string. In this article, we will learn how to concatenate two strings in C.The most straightforward method to concatenate two strings is by using strcat() function. Let's take a look at an example:C#include <stdio.h> #i
2 min read
Remove all occurrences of a character in a string
Given a string and a character, remove all the occurrences of the character in the string.Examples: Input : s = "geeksforgeeks" c = 'e'Output : s = "gksforgks"Input : s = "geeksforgeeks" c = 'g'Output : s = "eeksforeeks"Input : s = "geeksforgeeks" c = 'k'Output : s = "geesforgees"Using Built-In Meth
2 min read
Binary String
Check if all bits can be made same by single flip
Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the d
5 min read
Number of flips to make binary string alternate | Set 1
Given a binary string, that is it contains only 0s and 1s. We need to make this string a sequence of alternate characters by flipping some of the bits, our goal is to minimize the number of bits to be flipped. Examples : Input : str = â001â Output : 1 Minimum number of flips required = 1 We can flip
8 min read
Binary representation of next number
Given a binary string that represents binary representation of positive number n, the task is to find the binary representation of n+1. The binary input may or may not fit in an integer, so we need to return a string.Examples: Input: s = "10011"Output: "10100"Explanation: Here n = (19)10 = (10011)2n
6 min read
Min flips of continuous characters to make all characters same in a string
Given a string consisting only of 1's and 0's. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.Examples: Input : 00011110001110Output : 2We need to convert 1's sequenceso string consist of all 0's.Input
8 min read
Generate all binary strings without consecutive 1's
Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.Examples: Input : n = 4Output : 0000 0001 0010 0100 0101 1000 1001 1010Input : n = 3Output : 000 001 010 100 101Approach:The idea is to generate all binary strings of length n without consecutive 1's usi
6 min read
Find i'th Index character in a binary string obtained after n iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes "01" and 1 becomes "10". Find the (based on indexing) index character in the string after the nth iteration. Examples: Input : m = 5, n = 2, i = 3Output : 1Input : m = 3, n = 3, i = 6Output
6 min read
Substring and Subsequence
All substrings of a given String
Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string.Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c"Input : s = "ab"Output : "a", "ab", "b"Input : s = "a"Output : "a"[Expected Approach] - Using Iterati
8 min read
Print all subsequences of a string
Given a string, we have to find out all its subsequences of it. A String is said to be a subsequence of another String, if it can be obtained by deleting 0 or more character without changing its order.Examples: Input : abOutput : "", "a", "b", "ab"Input : abcOutput : "", "a", "b", "c", "ab", "ac", "
12 min read
Count Distinct Subsequences
Given a string str of length n, your task is to find the count of distinct subsequences of it.Examples: Input: str = "gfg"Output: 7Explanation: The seven distinct subsequences are "", "g", "f", "gf", "fg", "gg" and "gfg" Input: str = "ggg"Output: 4Explanation: The four distinct subsequences are "",
13 min read
Count distinct occurrences as a subsequence
Given two strings pat and txt, where pat is always shorter than txt, count the distinct occurrences of pat as a subsequence in txt.Examples: Input: txt = abba, pat = abaOutput: 2Explanation: pat appears in txt as below three subsequences.[abba], [abba]Input: txt = banana, pat = banOutput: 3Explanati
15+ min read
Longest Common Subsequence (LCS)
Given two strings, s1 and s2, the task is to find the length of the Longest Common Subsequence. If there is no common subsequence, return 0. A subsequence is a string generated from the original string by deleting 0 or more characters, without changing the relative order of the remaining characters.
15+ min read
Shortest Superstring Problem
Given a set of n strings arr[], find the smallest string that contains each string in the given set as substring. We may assume that no string in arr[] is substring of another string.Examples: Input: arr[] = {"geeks", "quiz", "for"}Output: geeksquizforExplanation: "geeksquizfor" contains all the thr
15+ min read
Printing Shortest Common Supersequence
Given two strings s1 and s2, find the shortest string which has both s1 and s2 as its sub-sequences. If multiple shortest super-sequence exists, print any one of them.Examples:Input: s1 = "geek", s2 = "eke"Output: geekeExplanation: String "geeke" has both string "geek" and "eke" as subsequences.Inpu
9 min read
Shortest Common Supersequence
Given two strings s1 and s2, the task is to find the length of the shortest string that has both s1 and s2 as subsequences.Examples: Input: s1 = "geek", s2 = "eke"Output: 5Explanation: String "geeke" has both string "geek" and "eke" as subsequences.Input: s1 = "AGGTAB", s2 = "GXTXAYB"Output: 9Explan
15+ min read
Longest Repeating Subsequence
Given a string s, the task is to find the length of the longest repeating subsequence, such that the two subsequences don't have the same string character at the same position, i.e. any ith character in the two subsequences shouldn't have the same index in the original string. Examples:Input: s= "ab
15+ min read
Longest Palindromic Subsequence (LPS)
Given a string s, find the length of the Longest Palindromic Subsequence in it. Note: The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Longest Palindromic SubsequenceExamples:Input: s = "bbabcbcab"Output: 7Explanation: Subsequen
15+ min read
Longest Palindromic Substring
Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring.Examples:Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "ee
12 min read
Palindrome
C Program to Check for Palindrome String
A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program.The simplest method to check for palindrome string is to reverse the given string and store it in a temp
4 min read
Check if a given string is a rotation of a palindrome
Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read
Check if characters of a given string can be rearranged to form a palindrome
Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
14 min read
Online algorithm for checking palindrome in a stream
Given a stream of characters (characters are received one by one), write a function that prints 'Yes' if a character makes the complete string palindrome, else prints 'No'. Examples:Input: str[] = "abcba"Output: a Yes // "a" is palindrome b No // "ab" is not palindrome c No // "abc" is not palindrom
15+ min read
Print all Palindromic Partitions of a String using Bit Manipulation
Given a string, find all possible palindromic partitions of a given string. Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions. Example: Input: nitinOut
10 min read
Minimum Characters to Add at Front for Palindrome
Given a string s, the task is to find the minimum number of characters to be added to the front of s to make it palindrome. A palindrome string is a sequence of characters that reads the same forward and backward. Examples: Input: s = "abc"Output: 2Explanation: We can make above string palindrome as
12 min read
Make largest palindrome by changing at most K-digits
You are given a string s consisting of digits (0-9) and an integer k. Convert the string into a palindrome by changing at most k digits. If multiple palindromes are possible, return the lexicographically largest one. If it's impossible to form a palindrome with k changes, return "Not Possible".Examp
14 min read
Minimum Deletions to Make a String Palindrome
Given a string s of length n, the task is to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome. Note: The order of characters should be maintained. Examples : Input : s = "aebcbda"Output : 2Explanation: Remove characters 'e' and 'd'. Resul
15+ min read
Minimum insertions to form a palindrome with permutations allowed
Given a string of lowercase letters. Find minimum characters to be inserted in the string so that it can become palindrome. We can change the positions of characters in the string.Examples: Input: geeksforgeeksOutput: 2Explanation: geeksforgeeks can be changed as: geeksroforskeeg or geeksorfroskeeg
5 min read