Leetcode easy problem 1047. Remove All Adjacent Duplicates In String, detailed explanation and solution in python language.
LeetCode Problem Link: https://leetcode.com/problems/remove-...
Solution (Python Code): https://github.com/shaheershukur/Leet...
#leetcode #python #solution
Problem Statement:
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.
______________________________________________________________
LeetCode problem solving helps in improving one's problem solving and coding skills . Also, it helps in clearing technical interviews at top tech companies like Microsoft, Google, Amazon, Facebook, Walmart, Apple etc.
(FAANGM, MAANGM, Product based companies)
CC of video:
we are given a string of lowercase English letters.
and we need to check whether there are any adjacent and equal letters in the string and remove them.
we need to do this repeatedly until there are no more adjacent and equal letters in the string.
In order to accomplish this in a single pass, we need to use a stack.
so what we will do is, we will iterate through the entire string from the first letter till the last letter.
during each iteration, we will push the current letter to the stack if the last letter already in the stack and the current letter are different.
and if they are same, we know that it will result in adjacent and equal letters, and we can thus delete them both.
i.e., we will pop out the last element from the stack.
so, by the end of the iterations, we will have the required result in the stack.
we just have to return it as a string.
lets code the solution.
first, we will have an empty stack initialized.
now, we will iterate through the string.
if the stack is empty, only thing we can do is to push the current letter into the stack.
and if the stack is not empty, we have two scenarios.
first scenario is, the last letter in the stack and the current letter are different.
in that case, we can push the current letter to the stack.
second scenario is, the last letter in the stack and the current letter are equal.
in that case, we need to delete both of them. so we will pop out the last element from the stack.
so, after the iteration, we have our result in the stack, and we need to join them together into a string without any gaps.
so we will pass the stack to the join method on an empty string, and return it.