Given a numeric string S consisting of N digits, the task is to find the minimum length of the string that can be formed by repeatedly removing pairs of adjacent consecutive characters arranged in either increasing or decreasing order.
Examples:
Input: S = “12213”
Output: 1
Explanation:
The minimum length of the string S that can be obtained by removing elements in following way:
- Remove substring {S[0], S[1]}. The string S modifies to “213”
- Remove substring {S[0], S[1]}. The string S modifies to “3”
Therefore, the length of the string S is 1, which is the minimum possible length.
Input: S = “1350”
Output: 4
Approach: The given problem can be solved using the Stack Data Structure. Follow the steps below to solve the problem:
Below is the implementation of this approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minLength(string S)
{
stack< char > st;
for ( auto ch : S) {
if (st.empty())
st.push(ch);
else {
char top = st.top();
if ( abs (ch - top) == 1)
st.pop();
else {
st.push(ch);
}
}
}
return st.size();
}
int main()
{
string S = "12213" ;
cout << minLength(S);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
static int minLength(String S)
{
Stack<Character> st = new Stack<>();
for ( char ch : S.toCharArray()) {
if (st.isEmpty())
st.push(ch);
else {
char top = st.peek();
if (Math.abs(ch - top) == 1 )
st.pop();
else {
st.push(ch);
}
}
}
return st.size();
}
public static void main(String[] args)
{
String S = "12213" ;
System.out.println(minLength(S));
}
}
|
Python3
def minLength(S):
st = []
for ch in S:
if ( len (st) = = 0 ):
st.append(ch)
else :
top = st[ - 1 ]
if ( abs ( ord (ch) - ord (top)) = = 1 ):
st.pop()
else :
st.append(ch)
return len (st)
if __name__ = = "__main__" :
S = "12213"
print (minLength(S))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int minLength(String S)
{
Stack< char > st = new Stack< char >();
foreach ( char ch in S.ToCharArray())
{
if (st.Count == 0)
st.Push(ch);
else
{
char top = st.Peek();
if (Math.Abs(ch - top) == 1)
st.Pop();
else
{
st.Push(ch);
}
}
}
return st.Count;
}
public static void Main(String[] args)
{
String S = "12213" ;
Console.WriteLine(minLength(S));
}
}
|
Javascript
<script>
function minLength(S)
{
var st = [];
S.split( '' ).forEach(ch => {
if (st.length==0)
st.push(ch);
else {
var top =st[st.length-1];
if (Math.abs(ch - top) == 1)
st.pop();
else {
st.push(ch);
}
}
});
return st.length;
}
var S = "12213" ;
document.write( minLength(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)