Skip to content
Related Articles
Minimize length of a string by removing pairs of consecutive increasing or decreasing digits
• Last Updated : 10 Jun, 2021

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:

1. Remove substring {S, S}. The string S modifies to “213”
2. Remove substring {S, S}. 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++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find the minimum length``// of the string possible after removing``// pairs of consecutive digits``int` `minLength(string S)``{``    ``// Initialize the stack st``    ``stack<``char``> st;` `    ``// Traverse the string S``    ``for` `(``auto` `ch : S) {` `        ``// If the stack is empty``        ``if` `(st.empty())``            ``st.push(ch);` `        ``// Otherwise``        ``else` `{` `            ``// Get the top character``            ``// of the stack``            ``char` `top = st.top();` `            ``// If cha and top are``            ``// consecutive digits``            ``if` `(``abs``(ch - top) == 1)``                ``st.pop();` `            ``// Otherwise, push the``            ``// character ch``            ``else` `{``                ``st.push(ch);``            ``}``        ``}``    ``}` `    ``// Print the size of the stack``    ``return` `st.size();``}` `// Driver Code``int` `main()``{``    ``string S = ``"12213"``;``    ``cout << minLength(S);` `    ``return` `0;``}`

## Java

 `// java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;` `public` `class` `GFG {` `    ``// Function to find the minimum length``    ``// of the string possible after removing``    ``// pairs of consecutive digits``    ``static` `int` `minLength(String S)``    ``{``        ``// Initialize the stack st``        ``Stack st = ``new` `Stack<>();` `        ``// Traverse the string S``        ``for` `(``char` `ch : S.toCharArray()) {` `            ``// If the stack is empty``            ``if` `(st.isEmpty())``                ``st.push(ch);` `            ``// Otherwise``            ``else` `{` `                ``// Get the top character``                ``// of the stack``                ``char` `top = st.peek();` `                ``// If cha and top are``                ``// consecutive digits``                ``if` `(Math.abs(ch - top) == ``1``)``                    ``st.pop();` `                ``// Otherwise, push the``                ``// character ch``                ``else` `{``                    ``st.push(ch);``                ``}``            ``}``        ``}` `        ``// Print the size of the stack``        ``return` `st.size();``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{` `        ``String S = ``"12213"``;``        ``System.out.println(minLength(S));``    ``}``}` `// This code is contributed by Kingash.`

## Python3

 `# Python 3 program for the above approach` `# Function to find the minimum length``# of the string possible after removing``# pairs of consecutive digits``def` `minLength(S):` `    ``# Initialize the stack st``    ``st ``=` `[]` `    ``# Traverse the string S``    ``for` `ch ``in` `S:` `        ``# If the stack is empty``        ``if` `(``len``(st) ``=``=` `0``):``            ``st.append(ch)` `        ``# Otherwise``        ``else``:` `            ``# Get the top character``            ``# of the stack``            ``top ``=` `st[``-``1``]` `            ``# If cha and top are``            ``# consecutive digits``            ``if` `(``abs``(``ord``(ch) ``-` `ord``(top)) ``=``=` `1``):``                ``st.pop()` `            ``# Otherwise, push the``            ``# character ch``            ``else``:``                ``st.append(ch)` `    ``# Print the size of the stack``    ``return` `len``(st)`  `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``S ``=` `"12213"``    ``print``(minLength(S))` `    ``# This code is contributed by ukasp.`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to find the minimum length``// of the string possible after removing``// pairs of consecutive digits``static` `int` `minLength(String S)``{``    ` `    ``// Initialize the stack st``    ``Stack<``char``> st = ``new` `Stack<``char``>();` `    ``// Traverse the string S``    ``foreach` `(``char` `ch ``in` `S.ToCharArray())``    ``{``        ` `        ``// If the stack is empty``        ``if` `(st.Count == 0)``            ``st.Push(ch);` `        ``// Otherwise``        ``else``        ``{``            ` `            ``// Get the top character``            ``// of the stack``            ``char` `top = st.Peek();` `            ``// If cha and top are``            ``// consecutive digits``            ``if` `(Math.Abs(ch - top) == 1)``                ``st.Pop();` `            ``// Otherwise, push the``            ``// character ch``            ``else``            ``{``                ``st.Push(ch);``            ``}``        ``}``    ``}` `    ``// Print the size of the stack``    ``return` `st.Count;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``String S = ``"12213"``;``    ``Console.WriteLine(minLength(S));``}``}` `// This code is contributed by shikhasingrajput`

## Javascript

 ``
Output:
`1`

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up