Google Interview Question for Software Engineers


Country: Korea
Interview Type: In-Person




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

Looking for interview experience sharing and coaching?

Visit AONECODE.COM for ONE-TO-ONE private lessons by FB, Google and Uber engineers!

SYSTEM DESIGN Courses (highly recommended for candidates of FB, LinkedIn, Amazon, Google & Uber etc.)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algorithms & Clean Coding),
latest interview questions sorted by companies,
mock interviews.

Our students got hired from G, U, FB, Amazon, LinkedIn, MS and other top-tier companies after weeks of training.

Email us aonecoding@gmail.com with any questions. Thanks!

#recursion
def reverse(html):
    if not html:
        return

    tag, html = stripOuterTag(html)
    listOfTrunks = divideTrunks(html)
    #print listOfTrunks
    if len(listOfTrunks) == 1:
        return listOfTrunks[0][::-1] if not tag else addTag(listOfTrunks[0][::-1], tag)
    
    listOfTrunks = listOfTrunks[::-1]
    listOfTrunks = [reverse(trunk) for trunk in listOfTrunks]
    
    return addTag("".join(listOfTrunks), tag)

#split up elements in the same level
'''e.g. "hello<P><c>xyz</c>ab</P><S>hi</S>"
into 
["hello", "<P><c>xyz</c>ab</P>", "<S>hi</S>"]
'''
def divideTrunks(html):
    ls = []
    while html:
        idxOfOpenP = html.find('<')
        if idxOfOpenP > 0:
            ls.append(html[0: idxOfOpenP])
            html = html[idxOfOpenP:]
        else:
            tag = html[1: html.find('>')]
            endTag = '</' + tag + '>'
            idxOfEndTag = html.find(endTag)
            ls.append(html[0: idxOfEndTag + len(endTag)])
            html = html[idxOfEndTag + len(endTag):]
    return ls

'''
remove and return the surrounding tag
e.g.   "<S>hi</S>" 
into 
<S>, "hi"
'''
def stripOuterTag(html):
    if not html or html[0] != '<':
        return None, html
    tag = html[: html.find('>') + 1]
    return tag, html[len(tag): len(html) - len(tag) -1]

- aonecoding May 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class HTMLReverser {
    public String reverseHtml(String s) {
        Stack<String> parts = new Stack<>();
        for (int i = 0; i < s.length(); ) {
            String token = getNextToken(s, i);
            String reverse = null;
            if (isTokenAnHtmlTag(token)) {
                reverse = reverseHtmlTag(token);
            } else if (token.equals("(") || token.equals(")")) {
                if (token.equals("(")) {
                    reverse = ")";
                } else {
                    reverse = "(";
                }
            } else {
                reverse = new StringBuilder(token).reverse().toString();
            }

            parts.push(reverse);
            System.out.println("Pushing on stack: " + reverse);
            i += token.length();
        }

        StringBuilder sb = new StringBuilder();
        while(!parts.empty()) {
            sb.append(parts.pop());
        }

        return sb.toString();
    }

    private String getNextToken(String s, int index) {
        String token;
        if (s.charAt(index) == '<') {
            int pos = s.indexOf('>', index);
            token = s.substring(index, (pos + 1));
        } else if (s.charAt(index) == '(' || s.charAt(index) == ')') {
            token = s.substring(index, index + 1);
        } else {
            int pos = index;
            char ch = s.charAt(pos);
            while (ch != '<' && ch != '>' && ch != '(' && ch != ')') {
                ch = s.charAt(pos);
                pos++;
            }
            token = s.substring(index, pos - 1);
        }

        //System.out.println("Returning token: " + token);
        return token;
    }

    private boolean isTokenAnHtmlTag(String token) {
        if (token.startsWith("<")) return true;
        return false;
    }

    private String reverseHtmlTag(String tag) {
        if (tag.startsWith("</")) {
            return tag.replace("</", "<");
        } else {
            return tag.replace("<", "</");
        }
    }

    @Test
    public void reverseHtmlTests() {
        String input = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>";
        HTMLReverser reverser = new HTMLReverser();
        //System.out.println(reverser.reverseHtml(input));
        Assert.assertEquals("<A>(<S>ih</S>)(<P>ba</P>)(olleh)</A>", reverser.reverseHtml(input));
    }
}

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

C++ Solution:

#include <iostream>
#include <stack>
using namespace std;

string reverseHtml(string input){

    //Push string into a stack
    stack<char> mstack;
    for(auto c : input){
        mstack.push(c);
    }

    //Unroll stack and reverse () and <>
    string pass1;
    while(!mstack.empty()){
        char c = mstack.top();
        if(c == '<') pass1+= '>';
        else if(c == '>') pass1+= '<';
        else if(c == '(') pass1+= ')';
        else if(c == ')') pass1+= '(';
        else pass1+= c;
        mstack.pop();
    }

    //Negate the tags
    string pass2;
    for(auto it = pass1.begin(); it != pass1.end(); ++it){
        if(*it == '/')
            continue;
        if(*it == '<'){
            pass2 += *it;
            auto itrun = it;
            while( *itrun != '>')
                ++itrun;
            --itrun;
            if(*itrun != '/')
                pass2 += '/';
        }else{
            pass2 += *it;
        }
    }
    return pass2;
}

int main()
{
    string input = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>";
    cout << "Reverse of"<<endl << input << "is" <<endl << reverseHtml(input) << endl;
}

Output:

Reverse of
<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>is
<A>(<S>ih</S>)(<P>ba</P>)(olleh)</A>

Process returned 0 (0x0) execution time : 0.025 s
Press any key to continue.

- Gabriel Feyer May 19, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String reverseHtml(String html){
		
		if(html.charAt(0) != '<' || html.charAt(html.length() - 1) != '>' || html.length() < 3)
			return "";
		String result, tag = "", tempTag = "";
		StringBuilder text = new StringBuilder();
		int startIdx = 0, endIdx = 0;
		
		tag = html.substring(1, html.indexOf('>'));
		
		if(html.charAt(html.indexOf('>') + 1) != '<')
			text.append(html.substring(html.indexOf('>') + 1, html.indexOf('<', 1)));
		
		startIdx = html.indexOf('<',1);
		
		if(!html.substring(startIdx, html.indexOf('>',startIdx)).equals("</" + tag)){
			html = html.substring(tag.length() + 2 + text.length(), html.length() - (tag.length() + 3));
			Deque<String> stack = new ArrayDeque<String>();
			
			while(html.length() != 0){
				tempTag = html.substring(1, html.indexOf('>'));
				endIdx = html.indexOf("</" + tempTag);
				endIdx += (tempTag.length() + 2);
				stack.push(reverseHtml(html.substring(0,endIdx + 1)));
				html = html.substring(endIdx + 1);
			}
		
			result = "<" + tag + ">";
			while(!stack.isEmpty()){
				result += stack.pop();
			}
			return result + text.reverse() + "</" + tag + ">";
		}
		return "<" + tag + ">" + text.reverse() + "</" + tag + ">";
	}

- Punjabi_Jatt May 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>"
list = []
reversed_str = ""
i = 0
while(i < len(str)):
    if(str[i:i+2] == "(<"):
        k = i+3
        while(str[k] != '<'):
            k = k+1
        list.append(str[k-1:(i+3):-1])
        reversed_str += str[i:i+4]
        reversed_str += str[k-1:(i+3):-1]
        reversed_str += str[k]
        i = k+1
        print(i)
    elif(str[i] == '(' and str[i+1] != '<'):
        k = i+1
        while(str[k] != ')'):
            k = k+1
        list.append(str[k-1:(i):-1])
        reversed_str += str[i]
        reversed_str += str[k-1:(i):-1]
        reversed_str += str[k]
        i = k
    else: 
        reversed_str += str[i]
    i = i + 1
print(reversed_str)

- Anonymous June 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>"
list = []
reversed_str = ""
param_str = ""
tag_string = ""
final_str = ""

i = 0
while(i < len(str)):
    if(str[i:i+2] == "(<"):
        param_str = ''
        k = i+3
        while(str[k] != '<'):
            k = k+1
        param_str += str[i:i+4]
        param_str += str[k-1:(i+3):-1]
        param_str += str[k:k+5]
        list.append(param_str)
        i = k+4
    elif(str[i] == '(' and str[i+1] != '<'):
        tag_string = ''
        k = i+1
        while(str[k] != ')'):
            k = k+1
        tag_string += str[i]
        tag_string += str[k-1:(i):-1]
        tag_string += str[k]
        list.append(tag_string)
        i = k
    else: 
        reversed_str += str[i]
    i = i + 1
list.reverse()
final_str += reversed_str[0:4]
for i in list:
    final_str += i 
final_str += reversed_str[-4:]
print(final_str)

- Anonymous June 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>"
list = []
reversed_str = ""
param_str = ""
tag_string = ""
final_str = ""

i = 0
while(i < len(str)):
    if(str[i:i+2] == "(<"):
        param_str = ''
        k = i+3
        while(str[k] != '<'):
            k = k+1
        param_str += str[i:i+4]
        param_str += str[k-1:(i+3):-1]
        param_str += str[k:k+5]
        list.append(param_str)
        i = k+4
    elif(str[i] == '(' and str[i+1] != '<'):
        tag_string = ''
        k = i+1
        while(str[k] != ')'):
            k = k+1
        tag_string += str[i]
        tag_string += str[k-1:(i):-1]
        tag_string += str[k]
        list.append(tag_string)
        i = k
    else: 
        reversed_str += str[i]
    i = i + 1
list.reverse()
final_str += reversed_str[0:4]
for i in list:
    final_str += i 
final_str += reversed_str[-4:]
print(final_str)

- Anonymous June 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

str = "<A>(hello)(<P>ab</P>)(<S>hi</S>)</A>"
list = []
unreversed_str = ""
param_str = ""
tag_string = ""
reversed_html = ""

i = 0
while(i < len(str)):
    if(str[i:i+2] == "(<"):
        param_str = ''
        k = i+3
        while(str[k] != '<'):
            k = k+1
        param_str += str[i:i+4]
        param_str += str[k-1:(i+3):-1]
        param_str += str[k:k+5]
        list.append(param_str)
        i = k+4
    elif(str[i] == '(' and str[i+1] != '<'):
        tag_string = ''
        k = i+1
        while(str[k] != ')'):
            k = k+1
        tag_string += str[i]
        tag_string += str[k-1:(i):-1]
        tag_string += str[k]
        list.append(tag_string)
        i = k
    else: 
        unreversed_str += str[i]
    i = i + 1
list.reverse()
reversed_html += unreversed_str[0:4]
for i in list:
    reversed_html += i 
reversed_html += unreversed_str[-4:]
print(reversed_html)

- Anonymous June 28, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sdf

- Anonymous May 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sdfsdf

- sfsdf May 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sfsdf

- sfsdf May 08, 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