Problem solution · Java

Remove All Adjacent Duplicates in String II

Remove All Adjacent Duplicates in String II: a Java solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
33 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Remove All Adjacent Duplicates in String II, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 33 lines of Java from the credited upstream file 1209.java.
  • The implementation keeps its working state in language-native values and containers.
  • 3 loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeRemove All Adjacent Duplicates in String II · JavaJava
Use this to learn the idea, then write your own version.
class Item {  public char c;  public int freq;  public Item(char c, int freq) {    this.c = c;    this.freq = freq;  }} class Solution {  public String removeDuplicates(String s, int k) {    StringBuilder sb = new StringBuilder();    LinkedList<Item> stack = new LinkedList<>();     for (final char c : s.toCharArray()) {      if (!stack.isEmpty() && stack.peek().c == c)        ++stack.peek().freq;      else        stack.push(new Item(c, 1));      if (stack.peek().freq == k)        stack.pop();    }     while (!stack.isEmpty()) {      Item item = stack.pop();      for (int i = 0; i < item.freq; ++i)        sb.append(item.c);    }     return sb.reverse().toString();  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗