Super Reduced String Hacker Rank

 Problem Link:


https://www.hackerrank.com/challenges/reduced-string/problem



Solution:


Stack<Character>stack=new Stack<Character>();
        
        for(int i=0;i<s.length();i++){
            if(stack.isEmpty()){
                stack.push(s.charAt(i));
            }
            else{
                if(stack.peek()==s.charAt(i)){
                    stack.pop();
                }
                else{
                    stack.push(s.charAt(i));
                }
            }
        }
        if(stack.size()!=0){
        StringBuilder sb=new StringBuilder();
        while(!stack.isEmpty()){
            sb.append(stack.pop());
        }
        sb.reverse();
        
        return sb.toString(); 
        }
        else{
            return "Empty String";
        }
        


TIME COMPLEXITY: O(String Length)

SPACE COMPLEXITY: O(1)

AUXILLARY SPACE:O(String Length)

TOTAL TEST CASES: 16

APPROACH:

Using Stacks.

Here we will use the same approach as we do for balanced parenthesis.
First, we will traverse the string and push characters in the stack.
If stacks peek is equal to the incoming character value then we will pop that character
and if not equal then we will push that character into the stack.

Ex :
if the string is aaa then stack ="" (initially)
Traversal start: stack=" a" now string is aaa (first a traversed)
Now stack. peek()=a is equal to incoming character ie a (at index 1) so it will pop
stack="" string traversed=aaa
now last a is left
so stack="a" string travered="aaa" string traversal full. stack result is a return output is a

If stack is empty or stack.size()==0 then we will return output as "Empty string".

Ex : string = aaaa stack=""

string = aaaa stack="a"
string = aaaa stack=""
string = aaaa stack="a"
string = aaaa stack=""

(String traversal is shown in bold).

return "Empty String" as output.



"Thanks For Reading.😇"

"Share Further To Increase Knowledge Treasure.😊"

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks