unknown Interview Question for Software Engineers


Country: United States
Interview Type: Phone Interview




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

#include <vector>
#include <stack>

using namespace std;

class Node {
	public:
		Node()
		{
			pos_opening_ = pos_closing_ = -1;
		}
		int pos_opening_, pos_closing_;
		vector<Node *> children_;
};

Node *Parse(string const &s)
{
	stack<Node *> st;
	st.push(new Node);
	for (int i = 0; i < s.size(); ++i) {
		if (s[i] == '[') {
			Node *n = new Node;
			n->pos_opening_ = i;
			st.top()->children_.push_back(n);
			st.push(n);
		} else if (s[i] == ']') {
			st.top()->pos_closing_ = i;
			st.pop();
		}
	}
	return st.top();
}

void Print(Node const *n) {
	cout << "[" << n->pos_opening_ << ", " << n->pos_closing_ << ", ";
	if (!n->children_.empty()) {
		for (int i = 0; i < n->children_.size(); ++i) {
			if (i != 0) {
				cout << ", ";
			}
			Print(n->children_[i]);
		}
		cout << "]";
	} else {
		cout << "null]";
	}
}

int main(int argvc, char const **argv)
{
	Node *root = Parse("[[]][]");
	Print(root);
	cout << "\n";
	return 0;
}

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

use a stack and vector and recursion

#include<iostream>
#include <vector>
#include <stack>
using namespace std;
bool printp(vector<std::pair<char, int>> s1, int s, int e)
{
	if (s > e)	return false;
	cout << s1[s].first << s1[s].second << "," << s1[e].second << ",";
	if (!printp(s1, s + 1, e - 1)) cout << "null";
	cout << s1[e].first;
	return true;
}
void Parse(string s)
{
	std::stack<char> s1;
	vector<std::pair<char, int>> t1;
	int first = 1;
	for (int i = 0; i < s.length(); i++)
	{
		t1.push_back(make_pair(s[i], i));
		if (s[i] == '[')
			s1.push('[');
		else
		{
			s1.pop(); if (s1.empty()){ if (!first) cout << ","; first = 0; printp(t1, 0, t1.size() - 1); t1.clear(); }
		}
	}
}
int main()
{
	Parse("[[]][]");
	return 0;
}

- kkr.ashish October 29, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class TranslateBracketArrangement {

    public static void main(String[] args) {
        final String s1 = "[[]][]";
        final String s2= "[][[]]";
        System.out.println(process(s1, 0, s1.length() - 1));
        System.out.println(process (s2, 0, s2.length()-1));
    }

    static String process(String s, int start, int end) {
        System.out.printf("start =%d, end=%d %n", start, end);
        List<String> result = new ArrayList<>();
        // handle base case []
        if (end == start + 1) return String.format("[%d,%d, null]", start, end);
        // handle base case ""
        if ( end <start+1) return "null";
        // else we have [*] where * needs parsing
        int p = start;
        int left = 0, right = 0, p1 = p;
        while (end >= p) {

            switch (s.charAt(p)) {
                case '[':
                    left++;
                    break;
                case ']':
                    right++;
                    break;
            }
            p++;
            if (left > 0 && right > 0 && (left == right)) {
                String partial = String.format("[%d,%d,%s]", p1, p1 + left + right - 1, process(s, p1 + 1, p1 + left + right - 2));
                result.add (partial);
                left= right =0;
                p1=p;
            }

        }
        return result.toString();

    }
}

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

In Kotlin, using a stack and StringBuilder.

fun main(args: Array<String>) {

  val output = parse("[[]][]")
  println( output )
}


fun parse( input: String ) : String{

  val output = StringBuilder()
  var currentPos = 0
  val stx = ArrayDeque<Int>()
  
  while( currentPos < input.length ){
    
    if ( input[currentPos] == '[' ){
      stx.push( currentPos )
    } else {
    
      val start = stx.pop()
      if ( start == currentPos-1 ){
        if ( start != 0 ) output.append(",")
        output.append("[$start,$currentPos,null]")
      } else {
        if ( start != 0 ) output.prepend(",")
        output.prepend("[$start,$currentPos")
        output.append("]")        
      }
    }
    
    currentPos++
  
}
  
  return output.toString()

}

fun StringBuilder.prepend( string: String ): StringBuilder{
  this.insert(0, string )
  return this
}

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

def parser(string):
    stack = []
    for item in enumerate(string):
        if(item[1]=="["):
            stack.append(item)
        else:
            sub = [0,item[0],None]
            close = False
            while(not close):
                last = stack.pop()
                if type(last) is list:
                    sub[2] = last
                else:
                    sub[0] = last[0]
                    stack.append(sub)
                    close = True
    return stack


print parser("[[[[]][]]][]")

- anas September 26, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def parser(string):
    stack = []
    for item in enumerate(string):
        if(item[1]=="["):
            stack.append(item)
        else:
            sub = [0,item[0],None]
            close = False
            while(not close):
                last = stack.pop()
                if type(last) is list:
                    sub[2] = last
                else:
                    sub[0] = last[0]
                    stack.append(sub)
                    close = True
    return stack


print parser("[[[[]][]]][]")

- anas September 26, 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