HackerRank Super Reduced String Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Super Reduced String Solution. This problem is a part of the HackerRank Algorithms Series.

Ezoicreport this adHackerRank Super Reduced String Solution
HackerRank Super Reduced String Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Super Reduced String Solution

Ezoicreport this adTask

Reduce a string of lowercase characters in range ascii[‘a’..’z’]by doing a series of operations. In each operation, select a pair of adjacent letters that match, and delete them.

Delete as many characters as possible using this method and return the resulting string. If the final string is empty, return Empty String

Example

s = ‘aab’

aab shortens to b in one operation: remove the adjacent a characters.

s = ‘abba’

Remove the two ‘b’ characters leaving ‘aa’. Remove the two ‘a’ characters to leave ”. Return ‘Empty String’.

Function Description

Complete the superReducedString function in the editor below.

superReducedString has the following parameter(s):

  • string s: a string to reduce

Returns

  • string: the reduced string or Empty String

Input Format

A single string, s.

Constraints

  • 1 <= length of s <= 100

Sample Input 0

aaabccddd

Sample Output 0

abd

Explanation 0

Perform the following sequence of operations to get the final string:

aaabccddd → abccddd → abddd → abd

Sample Input 1

aa

Sample Output 1

Empty String

Explanation 1

aa → Empty String

Sample Input 2

baab

Sample Output 2

Empty String

Explanation 2

baab → bb → Empty String

HackerRank Super Reduced String Solutions

Super Reduced String Solution in C

#include<stdio.h>
typedef unsigned u;
char S[111];u l=1;
int main()
{
	char c;
	while((c=getchar())<'a');
	do
	{
		S[l]=c;
		if(S[l]==S[l-1])--l;
		else++l;
	}
	while((c=getchar())>='a');
	S[l]='\0';
	printf("%s\n",l-1?S+1:"Empty String");
	return 0;
}

Super Reduced String Solution in Cpp

#include <iostream>
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdio>
#include<numeric>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<list>
#include<cmath>
#include<bitset>
#include<cassert>
#include<queue>
#include<stack>
#include<deque>
#include<cassert>
using namespace std;
typedef long long ll;
typedef long double ld;
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	string s;
	cin >> s;
	vector<char>st;
	for (int i = 0; i < (int)s.length(); i++)
	{
		if (!st.empty() && st.back() == s[i])
		{
			st.pop_back();
		}
		else
		{
			st.push_back(s[i]);
		}
	}
	if (st.empty())
	{
		printf("Empty String\n");
	}
	else
	{
		for (int i = 0; i < (int)st.size(); i++)
		{
			printf("%c", st[i]);
		}
		printf("\n");
	}
	return 0;
}

Super Reduced String Solution in Java

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*; 
import java.util.*;
import java.util.regex.*;
/*
	  br = new BufferedReader(new FileReader("input.txt"));
	  pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
	  br = new BufferedReader(new InputStreamReader(System.in));
	  pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */
public class Solution {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;
	public static void main(String[] args) throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		//int qq = 1;
		int qq = Integer.MAX_VALUE;
		//int qq = readInt();
		for(int casenum = 1; casenum <= qq; casenum++)	{
			String s = nextToken();
			LinkedList<Character> q = new LinkedList<Character>();
			for(int i = 0; i < s.length(); i++) {
				if(!q.isEmpty() && q.peekLast() == s.charAt(i)) {
					q.removeLast();
				}
				else {
					q.addLast(s.charAt(i));
				}
			}
			for(char out: q) {
				pw.print(out);
			}
			if(q.size() == 0) {
				pw.print("Empty String");
			}
			pw.println();
		}
		exitImmediately();
	}
	private static void exitImmediately() {
		pw.close();
		System.exit(0);
	}
	private static long readLong() throws IOException {
		return Long.parseLong(nextToken());
	}
	private static double readDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
	private static int readInt() throws IOException {
		return Integer.parseInt(nextToken());
	}
	private static String nextLine() throws IOException  {
		if(!br.ready()) {
			exitImmediately();
		}
		st = null;
		return br.readLine();
	}
	private static String nextToken() throws IOException  {
		while(st == null || !st.hasMoreTokens())  {
			if(!br.ready()) {
				exitImmediately();
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}
Ezoicreport this ad

Super Reduced String Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
s = raw_input()
while 1:
    i=0
    flag=0
    while i<len(s)-1:
        if s[i] == s[i+1]:
            s=s[:i]+s[i+2:]
            flag=1
        else:    
            i+=1
    
    if flag==0:
        break
if len(s)>0:        
    print s        
else:
    print 'Empty String'

Super Reduced String Solution using JavaScript

function processData(input) {
    //Enter your code here
    var continueReducing = true;
    var s = input.split('');
    
    while(continueReducing) {
        continueReducing = false;
        
        for(var i = 0; i < s.length; i++) {
            if (s[i] == s[i + 1]) {
                s[i] = '';
                s[i + 1] = '';
                i++;
                continueReducing = true;
            }
        }
        s = s.join('').split('');
    }
    
    console.log(s.length == 0 ? 'Empty String' : s.join(''));
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

Super Reduced String Solution in Scala

object Solution {
  val pairs = (('a' to 'z') zip ('a' to 'z')).map(s => "" + s._1 + s._2).toList
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    //println(pairs.mkString(" "))
    val res = reduce(sc.next)
    if (res.length == 0)
      println("Empty String")
    else
     println(res)
  }
  def reduce(str: String) = {
    def step(s: String) = {
      var aux = s
      for (pair <- pairs) {
        aux = aux.replaceAll(pair, "")
      }
      aux
    }
    var pre = str
    var post = step(pre)
    while (pre.length != post.length) {
      pre = post
      post = step(pre)
    }
    post
  }
}

Super Reduced String Solution in Pascal

program test;
uses sysutils;
var s,al,s1: string;
    i,j: integer;
    NotFound: boolean;
begin
al := '';
readln(s);
s:=ansilowercase(s);
NotFound := False;
for i:=1 to length(s) do
begin
    s1 := s[i];
    //writeln(al + ' ' + s1);
    if (Length(al)>0) then
    begin
      if al[Length(al)] = s1 then
      begin
        Delete(al, Length(al), 1);
      end
      else
      begin
        al := al + s1;
      end;
    end
    else
    begin
        al := al + s1;
    end;
end;
if Length(al)=0 then
    writeln('Empty String')
else    
    writeln(al);
end.

Disclaimer: This problem (Super Reduced String) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Electronics Shop Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad