1047. Remove All Adjacent Duplicates In String LeetCode Solution

In this guide, you will get 1047. Remove All Adjacent Duplicates In String LeetCode Solution with the best time and space complexity. The solution to Remove All Adjacent Duplicates In String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Remove All Adjacent Duplicates In String solution in C++
  4. Remove All Adjacent Duplicates In String solution in Java
  5. Remove All Adjacent Duplicates In String solution in Python
  6. Additional Resources
1047. Remove All Adjacent Duplicates In String LeetCode Solution image

Problem Statement of Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = “abbaca”
Output: “ca”
Explanation:
For example, in “abbaca” we could remove “bb” since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is “aaca”, of which only “aa” is possible, so the final string is “ca”.

Example 2:

Input: s = “azxxzy”
Output: “ay”

Constraints:

1 <= s.length <= 105
s consists of lowercase English letters.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1047. Remove All Adjacent Duplicates In String LeetCode Solution in C++

class Solution {
 public:
  string removeDuplicates(const string& S) {
    string ans;

    for (const char c : S)
      if (!ans.empty() && ans.back() == c)
        ans.pop_back();
      else
        ans.push_back(c);

    return ans;
  }
};
/* code provided by PROGIEZ */

1047. Remove All Adjacent Duplicates In String LeetCode Solution in Java

class Solution {
  public String removeDuplicates(final String S) {
    StringBuilder sb = new StringBuilder();

    for (final char c : S.toCharArray()) {
      final int n = sb.length();
      if (n > 0 && sb.charAt(n - 1) == c)
        sb.deleteCharAt(n - 1);
      else
        sb.append(c);
    }

    return sb.toString();
  }
}
// code provided by PROGIEZ

1047. Remove All Adjacent Duplicates In String LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.