Google Phone Interview
Anonymous User
1164

Given logs in a file with each line representing string as time, method name, enter (boolean)
enter -> true
exit -> false.
We need to process the input and print the parsed results in the formatted manner. Parsed results are of the form function name, exitTime - enterTime.

Input:
t1 main enter
t2 foo enter
t3 bar enter
t4 bar exit
t5 foo exit
t6 bar enter
t7 bar exit
t8 main exit
t9 foo enter
t10 foo exit

Output:
main t8 - t1
\t foo t5 - t2
\t\t bar t4 - t3
\t bar t7 - t6
foo t10 - t9

class R {
  long timestamp;
  String methodName;
  boolean enter;

  R(String logString) { 
}
}

List<String> createReport(List<String> logStrings) {
	Stack<R> s = new Stack<>();
	List<String> res = new ArrayList<>();
	int tab = 0;
	int index = 0;
	Map<String, Integer> stringIndex = new HashMap<>();
	for(String logString: logStrings) {
		R r = new R(logString);
		if(r.enter) {
			s.push(r);
			String functionEntryString = getFormattedString(r.methodName, tab);
			res.add(r.methodName);
			tab++;
			stringIndex.put(r.methodName, index);
			index++;
	} else {
			if(!s.isEmpty()) {
				R logStringOnTop = s.poll();
				if(!checkIfTheCorrectLog(r.methodName, logStringOnTop.methodName)) {
					throw new Exception(“Current log is not the same as Log on top of stack”);
				}
				long timeToExecute = r.timestamp - logStringOnTop.timestamp;
				int currentFunctionIndex = stringIndex.get(r.methodName);
				String currentString = res.get(currentFunctionIndex);
				currentString = currentString + “ ” + timeToExecute;
				res.set(currentFunctionIndex, currentString);	
				 tab--;
				} else {
					throw new Exception(“No Function has entered in the execution”);
				}
		}
	}
	
	if(!s.isEmpty()) {
		throw new Exception(“Improper log string);
	}

	return res;
}


private String getFormattedString(String inputString, int tab) {
		StringBuilder sb = new StringBuilder(“”);
		for(int i = 0; i < tab; i++) {
		sb.append(“\t”);
	}

	sb.append(inputString);

	return sb.toString();
}

private boolean checkIfTheCorrectLog(String s1, String s2) {
	return s1.equals(s2);
} 
Comments (4)