Minimize removal of non-equal adjacent characters required to make a given string empty


In this article, we'll be diving into a fascinating string manipulation problem. The problem statement is "Minimize removal of non-equal adjacent characters required to make a given string empty". This problem is a fantastic way to enhance your understanding of strings, character removal, and algorithmic thinking.

Problem Statement

Given a string, the task is to minimize the number of removal operations of non-equal adjacent characters required to make the given string empty. In one operation, you can remove any two adjacent characters that are not equal.

Solution Approach

The approach to solve this problem is using a stack data structure. We iterate over the characters of the string, and for each character, if the stack is not empty and the top of the stack is not equal to the current character, we pop the top character from the stack. Otherwise, we push the current character onto the stack. The number of operations required is the number of characters remaining in the stack at the end.

Example

Following are the programs to the above approach −

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

int minimizeRemovals(char* str) {
   int size = 0;
   char* stack = (char*)malloc(strlen(str) * sizeof(char));

   for (int i = 0; str[i] != '\0'; i++) {
      if (size > 0 && stack[size - 1] != str[i]) {
         size--; // Pop the top element from the stack
      } else {
         stack[size] = str[i]; // Push the character onto the stack
         size++;
      }
   }

   free(stack);
   return size;
}

int main() {
   char str[] = "abba";
   int operations = minimizeRemovals(str);
   printf("The minimum number of removal operations is: %d\n", operations);
   return 0;
}

Output

The minimum number of removal operations is: 0
#include <iostream>
#include <stack>
#include <string>
using namespace std;

int minimizeRemovals(string str) {
   stack<char> s;
   for (char c : str) {
      if (!s.empty() && s.top() != c) {
         s.pop();
      } else {
         s.push(c);
      }
   }
   return s.size();
}

int main() {
   string str = "abba";
   int operations = minimizeRemovals(str);
   cout << "The minimum number of removal operations is: " << operations << endl;
   return 0;
}

Output

The minimum number of removal operations is: 0
import java.util.Scanner;

public class Main {
   public static int minimizeRemovals(String str) {
      java.util.Stack<Character> stack = new java.util.Stack<>();
      for (char c : str.toCharArray()) {
         if (!stack.isEmpty() && stack.peek() != c) {
            stack.pop();  // Pop the top element from the stack
         } else {
            stack.push(c);  // Push the character onto the stack
         }
      }
      return stack.size();
   }

   public static void main(String[] args) {
      String str = "abba";
      int operations = minimizeRemovals(str);
      System.out.println("The minimum number of removal operations is: " + operations);
   }
}

Output

The minimum number of removal operations is: 0
def minimize_removals(s):
   stack = []
   for c in s:
      if stack and stack[-1] != c:  # Check if the stack is not empty and the top element is different from the current character
         stack.pop()  # Pop the top element from the stack
      else:
         stack.append(c)  # Push the character onto the stack
   return len(stack)

def main():
   s = "abba"
   operations = minimize_removals(s)
   print("The minimum number of removal operations is:", operations)

if __name__ == "__main__":
   main()

Output

The minimum number of removal operations is: 0

Explanation with a Test Case

When we pass this string to the minimizeRemovals function, it iterates over the characters of the string. The process goes as follows −

  • It pushes 'a' onto the stack.

  • Then it pushes 'b' onto the stack because 'b' is not equal to the top of the stack ('a').

  • When the next 'b' is encountered, it sees that the top of the stack is also 'b', so it doesn't perform a remove operation, and 'b' is pushed onto the stack.

  • Now the top of the stack is 'b', and the next character is 'a'. Since 'a' is not equal to 'b', it performs a remove operation by popping the top of the stack. Now the top of the stack is 'b'.

  • Finally, it encounters 'a' in the string, which is not equal to the top of the stack ('b'). Hence, it performs a remove operation by popping the top of the stack.

At the end of the function, there are no characters left in the stack, indicating that all non-equal adjacent characters have been removed from the string. Hence, the function returns 0, which is the minimum number of removal operations required to make the given string empty.

Conclusion

This problem provides a fantastic opportunity to use stack data structure for string manipulation. It's an excellent problem to practice your coding skills and to understand how to solve problems using stacks.

Updated on: 23-Oct-2023

721 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements