Amazon Interview Question for SDE-2s


Country: United States
Interview Type: Phone Interview




Comment hidden because of low score. Click to expand.
2
of 2 vote

def check_bracket(str):
    stack = list()
    for char in str:
        if char == '<' or char == '(' or char == '{' or\
           char == '[':
            stack.append(char)
        else:
            bracket = stack.pop()
            if char == '>' and bracket != '<' or\
               char == '}' and bracket != '{' or\
               char == ')' and bracket != '(' or\
               char == ']' and bracket != '[':
                return False
    return True

- Kool October 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

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;


}

- libertythecoder November 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

// 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.

- NoOne October 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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");
	}
}

- gunjan.prmr October 31, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
  }

}

- dnsh November 01, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
        }

- xyz November 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
	}

}

- Anonymous November 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Is this string considered balanced?
<({([)})]>

- Anonymous November 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

@Dmytri
i don't think this is the right solution - see these cases imo is incorrect:

cowbell pts/1 try>./a.out {[}]
String is balanced

cowbell pts/1 try>./a.out {{]]
String is balanced

- rravir November 27, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
    }
}

- edanir December 05, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#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";
}

- Salim Amrani December 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- ankitpatel2100 February 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;

	}
}

- heyitzmithlesh August 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

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.
}

- Dmytri November 01, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More