Amazon Interview Question for Quality Assurance Engineers


Country: United States
Interview Type: In-Person




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

c++, implementation

bool validParenthesis(string str) {
	int i, n;

	i = 0;
	n = 0;
	while (i < str.size()) {
		if (str[i] == '(') {
			n++;
		} else if (str[i] == ')') {
			if (n == 0) return false;
			n--;
		}
		i++;
	}

	return (n == 0);
}

- kyduke October 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How about )))((( ?

- madi.sagimbekov October 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

If first character is ')', then n is 0 and this function return false.

This function is working correctly with ')))((('.

If we check only one type of parentheses such as '()', we do not need to use stack. Stack need to check valid with multiple type of parentheses and brackets such as '(){}[]'.

- kyduke October 26, 2015 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

use stack, if it is "open" bracket push it into stack, else pop element from stack and check if it is "open" bracket, if yes - continue, else return false

Here is the code:

public class ValidExpr {
    public static void main(String[] args) {
        String expr = "()";
        System.out.println(isValid(expr));
    }
    
    public static boolean isValid(String input) {
        Stack<Character> stack = new Stack<>();
        for (Character c : input.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else {
                if (!stack.isEmpty()) {
                    char k = stack.pop();
                    if (k != '(') {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        
        return stack.isEmpty();
    }
}

- madi.sagimbekov October 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I think if

!stack.isEmpty()

is true, we simply have to pop the topmost. No need to compare because the popped element will always be '(' since that's all that is ever pushed in.

- Wanderer November 08, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

yes, you are right, enough to check if stack is empty or not

- madi.sagimbekov November 17, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

def isvalid(s):
    """Check if the expression given in string 's' is a valid arithmetic
    expression.
    
    Eg: (())()) - Invalid expression, (()()) - Valid expression

    >>> isvalid('(())())')
    False
    >>> isvalid('(()())')
    True
    """
    if not s:
        return 0
    ps = []  # stack of parentheses
    for c in s:
        if c in '()':
            if ps and ps[-1] == '(' and c == ')':
                ps.pop()
            else:
                ps.append(c)
    return len(ps) == 0


if __name__ == '__main__':
    import doctest
    doctest.testmod()

- constt October 24, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Go through the string recursively, count left and right parenthesis, if right > left return false,
if it reaches the end of string and left != right, return false else return true.

- justaguy October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.pocketlab.practice.algo.array;

import java.util.Stack;

/**
 * How to find if a given expression is a valid arithmetic expression?
 * Eg:(())()) - Invalid expression, (()()) - Valid expression
 * @author user
 *
 */
public class AMZ_ValidExp {

	public static final String START_BRACKET = "(";
	public static final String END_BRACKET = ")";

	public static void main(String args[]) {

		String exp = "(())())";
		validate(exp);
		
		exp = "(()())";
		validate(exp);
	}

	public static boolean validate(String exp) {

		Stack<String> stack = new Stack<String>();
		boolean valid = true;
		String[] arr = exp.split("");
		for (String a : arr) {
			if (a.equalsIgnoreCase(START_BRACKET)) {
				stack.push(a);
			} else {
				if (stack.isEmpty()) {
					valid = false;
					break;
				} else {
					stack.pop();
				}
			}
		}

		if (!stack.isEmpty()) {
			valid = false;
		}
		if (valid) {
			System.out.println("Valid Express > " + exp);
		} else {
			System.out.println("Invalid Express > " + exp);

		}
		return false;
	}
}

- Sanjay October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.pocketlab.practice.algo.array;

import java.util.Stack;

/**
 * How to find if a given expression is a valid arithmetic expression?
 * Eg:(())()) - Invalid expression, (()()) - Valid expression
 * @author user
 *
 */
public class AMZ_ValidExp {

	public static final String START_BRACKET = "(";
	public static final String END_BRACKET = ")";

	public static void main(String args[]) {

		String exp = "(())())";
		validate(exp);
		
		exp = "(()())";
		validate(exp);
	}

	public static boolean validate(String exp) {

		Stack<String> stack = new Stack<String>();
		boolean valid = true;
		String[] arr = exp.split("");
		for (String a : arr) {
			if (a.equalsIgnoreCase(START_BRACKET)) {
				stack.push(a);
			} else {
				if (stack.isEmpty()) {
					valid = false;
					break;
				} else {
					stack.pop();
				}
			}
		}

		if (!stack.isEmpty()) {
			valid = false;
		}
		if (valid) {
			System.out.println("Valid Express > " + exp);
		} else {
			System.out.println("Invalid Express > " + exp);

		}
		return false;
	}
}

- Sanjay October 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.io.*;
public class Solution {

static String findValidExpression(String arr){

int count = 0;

for(char s : arr.toCharArray()){

if(s=='('){
count++;
}
else{
count--;
}
if(count<0){
return "invalid";
}
}
return "valid";

}
public static void main(String[] arg) throws IOException{

System.out.println("Enter the string ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String a=br.readLine();
System.out.println("Expression is "+findValidExpression(a));

}
}

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

#include<stdio.h>
#include<stdlib.h>
int stack[50];
int top=-1;
void push(char elem)
{
	stack[++top]=elem;
}
char pop()
{
	char elem;
	elem=stack[top--];
	return elem;
}
int main()
{
	char str[50];
	int i=0,flag=0;
	char ch,elem;
	printf("enter expression");
	scanf("%s",str);
	while(str[i]!='\0')
	{
		if(str[i]=='('||str[i]=='{'||str[i]=='[')
		push(str[i]);
		i++;
		if(str[i]==')'||str[i]=='}'||str[i]==']')
		{
			elem=pop();
			if(str[i]==')'&&elem=='(')
			flag=1;
			else
			flag=0;
			if(str[i]=='}'&&elem=='{')
			flag=1;
			else
			flag=0;
			if(str[i]==']'&&elem=='[')
			flag=1;
			else
			flag=0;
		}
	}
	if(flag=1&&top<0)
	printf("properly nested");
	else
	printf("not properly nested");
	return 0;
}

- apoorva November 09, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def find_valid_exp(inp):
    count = 0
    cnt = 0
    x = ')'
    y = '('
    for i in inp:
        if i == x:
            count+=1
        else:
            cnt += 1
    if count == cnt:
        return "valid"
    else:
        return "Invalid"
        
        
print find_valid_exp("(())())")

- parashar.002 January 14, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Validation {
	static char open= '(';
	static char close = ')'	;	

	public static boolean isValid(byte[] expr) {
		int sum = 0;
		for(int i=0; i<expr.length; i++) {
			if(expr[i] == open) {
				sum++;
			}
			else if (expr[i] == close){
				sum--; 
				if (sum < 0) { 
					return false;}
			}
		}	
			if (sum == 0) {
				return true;}
				else {
					      return false;}
	}		
	public static void main(String[] args) {
          String expr = "())(";
         if  (isValid(expr.getBytes()) == true) {
        	 System.out.println("Valid Expression");
         }
         else {
        		 System.out.println("Invalid Expression");
        	 }
         }
	}

- eminsqa January 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void expressionChecker(String s)
	{
		//String s="()()()(((()))))()()";
		int left=0;
		if(s.length()%2==0)
		{
			if(s.charAt(0)==')')
			{
				System.out.println("invalid expression");
			}
			
			else
			{					
			  for(int i=0;i<s.length();i++)
			  {
				
				if(s.charAt(i)=='(')
				{
					left++;
				}
				
				if(s.charAt(i)==')'&& left>0)
				{
					left--;
				}				
				
			  }
			
			  if(left==0)
			  {
				  System.out.println("valid erxpression");
			  }
			  else
			  {
				  System.out.println("Invalid erxpression");
			  }
			  
		   }
		}
		else
		{
			System.out.println("invalid expression");
		}

}

- vijaydeep May 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void expressionChecker(String s)
	{
		//String s="()()()(((()))))()()";
		int left=0;
		if(s.length()%2==0)
		{
			if(s.charAt(0)==')')
			{
				System.out.println("invalid expression");
			}
			
			else
			{					
			  for(int i=0;i<s.length();i++)
			  {
				
				if(s.charAt(i)=='(')
				{
					left++;
				}
				
				if(s.charAt(i)==')'&& left>0)
				{
					left--;
				}				
				
			  }
			
			  if(left==0)
			  {
				  System.out.println("valid erxpression");
			  }
			  else
			  {
				  System.out.println("Invalid erxpression");
			  }
			  
		   }
		}
		else
		{
			System.out.println("invalid expression");
		}

}

- vijaydeep May 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

expr='(()))'
opr=[]
flag=0
for i in expr:
if i=='(':
opr.append(i)
elif i==')' and len(opr)>0:
if opr.pop()=='(':
continue
elif i==')' and len(opr)==0:
flag=1
break
if flag==0:
print 'expression is valid'
else:
print 'expression is not valid'

- Shweta July 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		String s = "()()()";
		String[] arrS = s.split("");
		int count = 0;
		ArrayList<String> al = new ArrayList<>(Arrays.asList(arrS));
		for(int i=0; i<al.size(); i++) {
			if(al.get(i).equals("(")) {
				al.remove(i);
				count++;
			}
		}
		if(al.size()==count) {
			System.out.println("Valid arithmetic expression");
		} else {
			System.out.println("Not an arithmetic expression");
		}
	}

- GK May 03, 2019 | 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