 GFG App
Open App Browser
Continue

# Minimum moves to empty a String by repeatedly deleting substrings with different start and end

Given a string str, the task is to find the minimum number of moves required to make str empty by deleting any substring whose starting and ending characters are different. If it is not possible to empty a string, return “-1“.

Examples:

Input: str = “abba”
Output: 2
Explanation: Follow the following steps to get the empty string: “abba” -> (delete ab) -> “ba” -> (delete ba) -> “”

Input: aba
Output: -1
Explanation: It is not possible to empty the given string.

Input: abc
Output: 1

Approach: The task can be solved on the basis of observations.

• If the first & last characters are not equal, then only one operation is needed
• Else, check if there exist any 2 indices, which don’t match with the first & last characters. If they exist, the minimum number of operations needed are two, else it is impossible to reduce the string to an empty string.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Function to find the number of moves` `// required to make the string empty.` `void` `numberOfMoves(string& str, ``int` `n)` `{` `    ``// If the first and the last` `    ``// character are different` `    ``if` `(str != str[n - 1]) {` `        ``cout << ``"1"``;` `        ``return``;` `    ``}`   `    ``// Check if there is a index i such that` `    ``// s[i] != s and s[i+1] != s[n-1]` `    ``for` `(``int` `i = 0; i < n - 1; i++) {` `        ``if` `(str[i] != str` `            ``&& str[i + 1] != str[n - 1]) {` `            ``cout << ``"2"``;` `            ``return``;` `        ``}` `    ``}`   `    ``// If no such index exists then` `    ``// the answer is -1` `    ``cout << -1;` `    ``return``;` `}`   `// Driver Code` `int` `main()` `{` `    ``string str = ``"abba"``;` `    ``int` `n = 4;` `    ``numberOfMoves(str, n);` `}`

## Java

 `// Java code for the above approach` `import` `java.io.*;`   `class` `GFG ` `{`   `  ``// Function to find the number of moves` `  ``// required to make the string empty.` `  ``static` `void` `numberOfMoves(String str, ``int` `n)` `  ``{`   `    ``// If the first and the last` `    ``// character are different` `    ``if` `(str.charAt(``0``) != str.charAt(n-``1``)) {` `      ``System.out.println(``"1"``);` `      ``return``;` `    ``}`   `    ``// Check if there is a index i such that` `    ``// s[i] != s and s[i+1] != s[n-1]` `    ``for` `(``int` `i = ``0``; i < n - ``1``; i++) {` `      ``if` `(str.charAt(i) != str.charAt(``0``)` `          ``&& str.charAt(i+``1``) != str.charAt(n-``1``)) {` `        ``System.out.println(``"2"``);` `        ``return``;` `      ``}` `    ``}`   `    ``// If no such index exists then` `    ``// the answer is -1` `    ``System.out.println(-``1``);` `    ``return``;` `  ``}`   `  ``// Driver Code` `  ``public` `static` `void` `main (String[] args) {` `    ``String str = ``"abba"``;` `    ``int` `n = ``4``;` `    ``numberOfMoves(str, n);`   `  ``}` `}`   `// This code is contributed by Potta Lokesh`

## Python3

 `# Python program for the above approach`   `# Function to find the number of moves` `# required to make the string empty.` `def` `numberOfMoves(``str``, n):` `  `  `    ``# If the first and the last` `    ``# character are different` `    ``if` `(``str``[``0``] !``=` `str``[n ``-` `1``]):` `        ``print``(``"1"``)` `        ``return`   `    ``# Check if there is a index i such that` `    ``# s[i] != s and s[i+1] != s[n-1]` `    ``for` `i ``in` `range``(``0``, ``len``(``str``)):` `        ``if` `(``str``[i] !``=` `str``[``0``] ``and` `            ``str``[i ``+` `1``] !``=` `str``[n ``-` `1``]):` `                `  `            ``print``(``"2"``)` `            ``return`   `    ``# If no such index exists then` `    ``# the answer is -1` `    ``print``(``-``1``)` `    ``return`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `    `  `    ``str` `=` `"abba"` `    ``n ``=` `4``;` `    ``numberOfMoves(``str``, n);`   `    ``# This code is contributed by Samim Hossain Mondal.`

## C#

 `// C# program for the above approach` `using` `System;`   `public` `class` `GFG` `{`   `// Function to find the number of moves` `// required to make the string empty.` `static` `void` `numberOfMoves(``string` `str, ``int` `n)` `{` `  `  `    ``// If the first and the last` `    ``// character are different` `    ``if` `(str != str[n - 1]) {` `        ``Console.WriteLine(``"1"``);` `        ``return``;` `    ``}`   `    ``// Check if there is a index i such that` `    ``// s[i] != s and s[i+1] != s[n-1]` `    ``for` `(``int` `i = 0; i < n - 1; i++) {` `        ``if` `(str[i] != str` `            ``&& str[i + 1] != str[n - 1]) {` `            ``Console.WriteLine(``"2"``);` `            ``return``;` `        ``}` `    ``}`   `    ``// If no such index exists then` `    ``// the answer is -1` `    ``Console.WriteLine(-1);` `    ``return``;` `}`   `// Driver Code` `public` `static` `void` `Main(String []args) {` `    `  `    ``string` `str = ``"abba"``;` `    ``int` `n = 4;` `    ``numberOfMoves(str, n);` `}` `}`   `// This code is contributed by target_2.`

## Javascript

 ``

Output

`2`

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

My Personal Notes arrow_drop_up