Amazon Interview Question
SDE-2sCountry: United States
Interview Type: Phone Interview
Easy and adaptable solution:
private final static HashMap<Char, Char> parenthesis = new HashMap<>();
static{
parenthesis.add(“(“, “)”);
parenthesis.add(“<“, “>”);
parenthesis.add(“{“, “}”);
parenthesis.add(“[“, “]”);
}
public boolean isBalanced(String str){
Stack<Character> stack = new Stack<>();
for(Char c : str.toCharArray()){
if(parenthesis.contains(c)){
stack.push(c);
}else{
if(parenthesis.(stack.pop()) != c)
return false;
}
}
if(stack.isEmpty())
return true;
return false;
}
// ZoomBA
paren_arr = [ { _'<' : 1 , _'>' : -1 , 'c' : 0 },
{ _'(' : 1 , _')' : -1 , 'c' : 0 },
{ _'{' : 1 , _'}' : -1 , 'c' : 0 },
{ _'[' : 1 , _']' : -1 , 'c' : 0 } ]
// now the indexing
parens = { _'<' : 0 , _'>' : 0 ,
_'(' : 1 , _')' : 1 ,
_'{' : 2 , _'}' : 2 ,
_'[' : 3 , _']' : 3 }
def match_paren(string){
fold ( string.value , true ) -> {
matcher = paren_arr[ parens[ $.item ] ]
matcher.c += matcher[ $.item ]
break ( matcher.c < 0 ){ false }
true
} && ! ( exists ( paren_arr ) :: { $.item.c != 0 } )
}
println ( match_paren ( "<({()})[]>" ) )
println ( match_paren ( "<({([)})[]>" ) )
This is fully declarative. The logic is actually implemented in the maps, while the engine simply runs it through, also fully extensible.
public static void BalanceStrings()
{
var patternList = new List<string>() { "<({()})[]>" , "<({([)})[]>" };
char[] allowedChars = { '(', '[', '{', ')', ']', '}', '<', '>' };
var updatedPattern = new StringBuilder();
foreach (var pattern in patternList)
{
var patternToCharacters = pattern.ToCharArray();
foreach (var character in patternToCharacters)
{
var isMatch = allowedChars.Any(x => x == character);
if (isMatch)
{
updatedPattern.Append(character);
}
}
Console.WriteLine(pattern.Equals(updatedPattern.ToString()) ? "balanced" : "Not balanced");
}
}
import java.util.*;
class BalancedString {
public static void main(String[] args) {
System.out.println(isBalanced("<({()})[]>"));
System.out.println(isBalanced("<({([)})[]>"));
}
public static boolean isBalanced(String s) {
Stack<String> stack = new Stack<>();
HashMap<String, String> map = new HashMap<>();
map.put("(", ")");
map.put("{", "}");
map.put("[", "]");
map.put("<", ">");
for (int i=0; i<s.length(); i++) {
String current = s.charAt(i) + "";
if (!stack.isEmpty() && map.get(stack.peek()) != null && map.get(stack.peek()).equals(current)) {
stack.pop();
} else {
stack.push(current);
}
}
return stack.isEmpty();
}
}
Tested in C# and also can be extended easily
static string openingChars = "<{[(";
static string closingChars = ">}])";
static bool IsBalanced(IEnumerable<char> characters)
{
int[] counters = new int[openingChars.Length];
int i = 0;
foreach (var c in characters)
{
i = openingChars.IndexOf(c);
if (i != -1)
{
counters[i]++;
continue;
}
i = closingChars.IndexOf(c);
if (i != -1)
{
if (counters[i] == 0) return false;
else counters[i]--;
}
}
for (i = 0; i < counters.Length; i++)
{
if (counters[i] != 0)
{
return false;
}
}
return true;
}
import java.util.ArrayList;
import java.util.Scanner;
public class BalancedString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
ArrayList<Character> stack = new ArrayList<>();
stack.add(str.charAt(0));
for(int i=1; i<str.length(); i++){
if((str.charAt(i) == ')' && stack.get(0) == '(') ||
(str.charAt(i) == '}' && stack.get(0) == '{') ||
(str.charAt(i) == ']' && stack.get(0) == '[') ||
(str.charAt(i) == '>' && stack.get(0) == '<'))
stack.remove(0);
else
stack.add(0, str.charAt(i));
}
if(stack.isEmpty())
System.out.println("Balanced");
else
System.out.println("not");
in.close();
}
}
class CheckCode{
public static boolean check(String s){
Stack ll = new Stack();
HashMap<Character,Character> map = new HashMap<Character,Character>();
map.put('{', '}');
map.put('(', ')');
map.put('[', ']');
char c;
char k;
if (s == null) return false;
for (int i = 0;i<s.length();i++){
c = s.charAt(i);
if (map.get(c) != null) {
ll.push(c);
}
if (map.containsValue(c)){
if (ll.peek() != null) {
k = (char) ll.pop();
if (map.get(k) != c) return false;
}
else return false;
}
}
return ll.peek() == null;
}
}
#include<iostream>
#include<stack>
#include<string>
using namespace std;
// Function to check whether two characters are opening
// and closing of same type.
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool AreParanthesesBalanced(string exp)
{
stack<char> S;
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !ArePair(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
/*Code to test the function AreParanthesesBalanced*/
string expression;
cout<<"Enter an expression: "; // input expression from STDIN/Console
cin>>expression;
if(AreParanthesesBalanced(expression))
cout<<"Balanced\n";
else
cout<<"Not Balanced\n";
}
def CheckIfBalance(mystring):
stack = list()
for eachchar in mystring:
if eachchar == '(' or eachchar == '{' or eachchar == '[' or eachchar == '<':
stack.append(eachchar)
elif eachchar == ')' and len(stack) > 0 and stack.pop() == '(':
continue
elif eachchar == '}' and len(stack) > 0 and stack.pop() == '{':
continue
elif eachchar == ']' and len(stack) > 0 and stack.pop() == '[':
continue
elif eachchar == '>' and len(stack) > 0 and stack.pop() == '<':
continue
else:
return "Not Balanced"
if len(stack) == 0:
return "Balanced"
else:
return "Not Balanced"
print CheckIfBalance("<({()})[]>") #Returns Balanced
print CheckIfBalance("<({([)})[]>") #Returns Not Balanced
print CheckIfBalance("))((") #Returns Not Balanced
print CheckIfBalance("((()") #Returns Not Balanced
public class ParenthesesBalance {
private final static HashMap<Character, Character> parenthesis = new HashMap<Character, Character>();
static {
parenthesis.put('(', ')');
parenthesis.put('<', '>');
parenthesis.put('{', '}');
parenthesis.put('[', ']');
}
public static void main(String[] args) {
String input = "[[()]]";
System.out.println("Is Balanced : " + isBalanced(input));
}
static public boolean isBalanced(String str) {
Stack<Character> stack = new Stack<Character>();
for (Character c : str.toCharArray()) {
if (parenthesis.containsKey(c)) {
stack.push(c);
} else {
if ( stack.isEmpty() || parenthesis.get(stack.pop()) != c)
return false;
}
}
if (stack.isEmpty())
return true;
return false;
}
}
Using counter to determine whether string is balanced.
#include <stdio.h> // Input-Output requests
int main(int argc, char** argv) {
char *paren = argv[1];
int counter = 0; // Counters for these
while (*paren != '\0') {
switch(*paren) {
case '{':
case '(':
case '[':
counter++;
break;
case '}':
case ')':
case ']':
counter--;
break;
}
paren++;
}
if (counter == 0)
printf("String is balanced\n");
else
printf("String is not balanced.\n");
return 0; // Successfully quit.
}
- Kool October 31, 2016