Bloomberg LP Interview Question for Interns


Country: United States
Interview Type: Phone Interview




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

def validateStr(s):
    braces = {'(':')', '[':']', '{':'}', '<':'>'}
    
    closing = [v for _,v in braces.items()]
    
    stack = []
    for c in s:
        if c in braces:
            stack.append(braces[c])
        elif c in closing:
            if len(stack) and c == stack[-1]:
                del stack[-1]
            else:
                print("%-15s\tInvalid. Unpaired %c"%(s,c))
                return False
    if len(stack):
        print("%-15s\tInvalid. Not closed braces: %s"%(s,"".join(stack)))
        return False
    print("%-15s\tok"%(s))
    return True

validateStr("([<>])")
validateStr("([<")
validateStr(")([<>])(")
validateStr("([)]")
validateStr("([<!#%^&>])")

Output:

([<>])         	ok
([<            	Invalid. Not closed braces: )]>
)([<>])(       	Invalid. Unpaired )
([)]           	Invalid. Unpaired )
([<!#%^&>])    	ok

- Diana.Savvatina November 05, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test {
    static List<String> validList=new ArrayList<>(Arrays.asList("<",">","{","}","[","]","(",")"));
public static void main(String [] args){
String s="(({[<>]}))";

    char [] chars =s.toCharArray();
    String b="";
    boolean isValid=true;
    for(int i=0;i<chars.length/2;i++){
        b=Character.toString(chars[i])+Character.toString(chars[chars.length-i-1]);
        if(!isValidBracketPair(b)){
            isValid=false;
            break;
        }
    }

    if(s.length()%2!=0){
        char middle=chars[s.length()/2+1];
        if(validList.contains(Character.toString(middle))){
            isValid=false;
        }
    }
    System.out.println("result of " + s + " "+ isValid);
}


public static boolean isValidBracketPair(String b){
    List<String> validList= new ArrayList<>();
    validList.add("{}");
    validList.add("[]");
    validList.add("()");
    validList.add("<>");
    return validList.contains(b) || isNotBracket(Character.toString(b.charAt(0)),Character.toString(b.charAt(1)));
}

    public static boolean isNotBracket(String a, String b){
   return  ! validList.contains(a) && ! validList.contains(b);

    }

}

- Akib November 07, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is how I'd do it
1 push on (,{,[,<
2 pop on ),},],>
compare popped value
the fail conditions are
1 no opening brace
2 opening brace not matching with closing brace
3 unsatisfied opening braces
the success condition would be all braces matching in the right order
i.e stack empty at end

public class BracketChk {
    static Stack<Character> stack = new Stack<>();
    
    public static void main(String[] args) {
        System.out.print("Enter the String with brackets : ");
        String input = (new Scanner(System.in)).nextLine();
        try {
            for (int i = 0; i < input.length(); i++) {
                System.out.println(stack.toString());
                char c = input.charAt(i);
                boolean flag = true;
                switch (c) {
                    case '(': case '{': case '[': case '<':
                        stack.push(c);
                        break;
                    case ')': case '}': case ']': case '>':
                        char o = stack.pop(); // closing brace not having any opening brace
                                              // throws exception
                        switch (c) {
                            case ')':
                                if (o != '(') flag = false;
                                break;
                            case '}':
                                if (o != '{') flag = false;
                                break;
                            case ']':
                                if (o != '[') flag = false;
                                break;
                            case '>':
                                if (o != '<') flag = false;
                                break;
                        }
                }
                if (!flag) throw new EmptyStackException(); // opening and closing brace not matching
            }
            if (stack.size() > 0) throw new EmptyStackException(); // more opening braces
            System.out.println("Successful : Brackets balanced!!"); // all braces match
        }
        catch (EmptyStackException e) {
            System.out.println("Unsuccessful : Brackets not balanced");
        }
    }
}

- PeyarTheriyaa November 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Like others mentioned using a stack and a dictionary of open and close characters this is trivial to implement. O(n) Python 3 implementation:

def validate_string(s, brackets_dict):
    stack = []
    open_bracket = set(brackets_dict.keys())
    close_bracket = set(brackets_dict.values())
    open = False
    for char in s:
        if not open:
            if char in close_bracket:
                return False
            open = True
            stack.append(brackets_dict[char])
        else:
            if char in open_bracket:
                stack.append(brackets_dict[char])
            else:
                if not char == stack.pop():
                    return False
                if len(stack) == 0:
                    open = False

    return True


if __name__ == '__main__':
    s = '{{[]}}'
    validate_string(s, {'{': '}', '[': ']'})

- sjjpo2002 November 09, 2018 | 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