Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: In-Person




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

In the above example why is the second string invalid ? Is it invalid because the " and ' don't have a matching closing " or ' ? Or is it invalid because of the empty ()

- RAV January 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

I considered a case when everything that inside quotes like "smth." or 'smth.' should be ignored.
So, my solution is:

private final static Map<Character, Character> symbolsPairs = new HashMap<>();
  private final static Set<Character> brackets = new HashSet<>();
  private final static Set<Character> quotes = new HashSet<>();

  static {
    // Brackets
    brackets.add('<');
    brackets.add('>');
    brackets.add('{');
    brackets.add('}');
    brackets.add('[');
    brackets.add(']');
    brackets.add('(');
    brackets.add(')');
    // Quotes
    quotes.add('\'');
    quotes.add('\"');
    // Pairs
    symbolsPairs.put('(', ')');
    symbolsPairs.put('<', '>');
    symbolsPairs.put('{', '}');
    symbolsPairs.put('[', ']');
  }

  public static void main(String[] args) {
    try (Scanner in = new Scanner(System.in)) {
      int T = in.nextInt();

      StringBuilder output = new StringBuilder();
      for (int t = 0; t < T; t++) {
        boolean isBalanced = hasBalancedBracketsAndQuotes(in.next());
        output.append(isBalanced ? "Yes" : "No").append(System.lineSeparator());
      }
      System.out.print(output);
    }
  }
  
  static boolean hasBalancedBracketsAndQuotes(String s) {
    LinkedList<Character> stack = new LinkedList<>();
    boolean hasDoubleQuote = false;
    boolean hasSingleQuote = false;
    for (int i = 0; i < s.length(); i++) {
      char b = s.charAt(i);
      if (!brackets.contains(b) && !quotes.contains(b)) {
        continue;
      }

      if (hasDoubleQuote && b == '\"') {
        hasDoubleQuote = false;
        continue;
      }

      if (hasSingleQuote && b == '\'') {
        hasSingleQuote = false;
        continue;
      }
      // to check brackets only we are not inside quotes
      if (!hasDoubleQuote && !hasSingleQuote) {
        if (symbolsPairs.containsKey(b)) {
          stack.addLast(b);
        } else if (quotes.contains(b)) {
          if (b == '\"') {
            hasDoubleQuote = true;
          }
          if (b == '\'') {
            hasSingleQuote = true;
          }
        } else {
          // to check that closed bracket is matched to open bracket
          Character o = stack.pollLast();
          if (o == null || !symbolsPairs.get(o).equals(b)) {
            return false;
          }
        }
      }
    }

    if (!stack.isEmpty() || hasDoubleQuote || hasSingleQuote) {
      return false;
    }

    return true;
  }

Tests are:
a{a{"a{{a"a}a}a - Yes
a{a{'a{{a'a}a}a - Yes
a{a{'a{{a"a}a}a - No
a{a{'a{{a"a}a}a - No
a{a{"a{{a}a"a}a - No
a{a{'a{{a}a'a}a - No
a{[a'a"a'a"a'a"a]a}a - Yes
a{[a'a'a'a"a'a"a]a}a - No
a{[a'a)a'a'a{a'a'a<a'a]a}a - Yes
a - Yes
a{a"a'a"a}a - Yes
a{a"a"a}a - Yes
a{{a'a}}'a}a} - Yes
<a{a(a[a"a}a]a>a)"a]a)a}a> - Yes
<a{a(a[a"a}a]a>a)"a>a}a)a] - No
a"a'a - No
a'a"a - No

- Mike L January 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

In the above example why is the second string invalid ? Is it invalid because the " and ' don't have a matching closing " or ' ? Or is it invalid because of the empty ()

- Anonymous January 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static bool Verify(string input)
        {
            Dictionary<char, char> OpeningClosing = new Dictionary<char, char>();
            OpeningClosing.Add(')', '(');
            OpeningClosing.Add('}', '{');
            OpeningClosing.Add(']', '[');
            Stack<char> stack = new Stack<char>();
            int count = 0;

            for (int i = 0; i < input.Length; i++)
            {
                if (OpeningClosing.ContainsValue(input[i]))
                {
                    stack.Push(input[i]);
                    count = 0;
                }
                else if (OpeningClosing.ContainsKey(input[i]))
                {
                    if (stack.Count == 0)
                    {
                        return false;
                    }

                    var closing = stack.Pop();
                    if (closing != OpeningClosing[input[i]] || count == 0)
                    {
                        return false;
                    }
                }
                else
                {
                    count++;
                }
            }

            if (stack.Count != 0)
            {
                return false;
            }
            return true;
        }

- smart artist January 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Because of quotes. You have to do validation for quotes also.i was not able to do validation for quotes because while processing string i was not able to find the way which tells quote is starting quote or end quote.

- djvirus January 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

module.exports = function (s) {
  var S = []
  for (var i = 0; i < s.length; ++i) {
    var char = s.charAt(i)
    var j = S.length - 1
    if (char === '\'' || char === '\"') {
      if (S[j] === char) {
        S.pop()
      } else {
        S.push(char)
      }
      continue
    }
    if (char === '(' || char === '{') {
      S.push(char)
    }
    if (char === ')') {
      if (S[j] === '(') {
        S.pop()
        continue
      } else  {
        return false
      }
    }
    if (char === '}') {
      if (S[j] === '{') {
        S.pop()
        continue
      } else {
        return false
      }
    }
  }
  return S.length === 0
}

var s = '\"A(\'\')B\"'
var solution = module.exports(s)
console.log(solution)

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

@Mike L I think yours is good, but I don't think you have to assume a syntactical insignificance to anything within either double or single quotes.

So something like this in my mind should still be false

```
a{a{"a{{a"a}a}a
```

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

iparens = iter('(){}[]<>\'')
parens = dict(zip(iparens, iparens))
closing = parens.values()

def balanced(astr):
    stack = []
    for c in astr:
        d = parens.get(c, None)
        if d:
            stack.append(d)
        elif c in closing:
            if not stack or c != stack.pop():
                return False
    return not stack

- revanthpobala January 25, 2017 | 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