In this Super Reduced String HackerRank solution, 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.
aab
shortens to b
in one operation: remove the adjacent a
characters.
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, .
Super Reduced String HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in Python
def superReducedString(s):
stack = []
for c in s:
if stack and c == stack[-1]:
stack.pop(-1)
else:
stack.append(c)
ans=''.join(stack)
return ans if len(ans)>0 else 'Empty String'
Problem Solution in Java
public static String superReducedString(String s) {
if(s.length() == 0){
return "Empty String";
}
StringBuilder str = new StringBuilder(s);
for(int i = 0; i < s.length() - 1; i++){
if(s.charAt(i) == s.charAt(i + 1)){
return superReducedString(str.delete(i, i + 2).toString());
}
}
return s;
}
Problem Solution in JavaScript
function superReducedString(s) {
if(s.length === 0) return 'Empty String';
for(let i = 0; i < s.length; i++) {
if(s[i] === s[i + 1]) {
s = s.slice(0, i) + s.slice(i+2, s.length);
return superReducedString(s);
}
}
return s;
}
Problem Solution in C++
string superReducedString(string s) {
while (!s.empty()) {
for (int i = 0; i < s.size() - 1; i++) {
if (s[i] == s[i + 1]) {
s[i] = s[i + 1] = '0';
i++;
}
}
string result = "";
for (const auto& c : s)
if (c != '0')
result.push_back(c);
if (result == s)
return s;
s = result;
}
return "Empty String";
}
Problem Solution in C#
public static string superReducedString(string s)
{
List<char> chars = s.ToCharArray().ToList();
int i = 0;
while (i < chars.Count - 1) {
char charA = chars[i];
char charB = chars[i + 1];
if (charA == charB) {
chars.RemoveRange(i, 2);
if (i > 0) i--;
} else {
i++;
}
}
return chars.Count == 0 ? "Empty String" : new string(chars.ToArray());
}
Leave a Reply