Google Interview Question
Country: United States
function intoTable(list, width) {
let lines = [];
let lineCounter = 0;
let currLine = "";
for (let i = 0; i < list.length; i++) {
let word = list[i];
if(lineCounter + word.length + 1 < width) {
currLine += lineCounter == 0? word: " " + word;
lineCounter += word.length;
} else {
currLine += " |";
lines.push(currLine);
currLine = "";
lineCounter = 0;
}
}
currLine += " |";
lines.push(currLine);
return lines.join("\n");
}
StringBuilder output = new StringBuilder();
int appendedSoFar = 0;
for (String str : strings) {
int remaining = charPerLine - appendedSoFar;
if (remaining >= str.length()) {
if(remaining != charPerLine) {
output.append(" ");
}
output.append(str);
appendedSoFar += str.length() + 1;
} else {
output.append("\n");
output.append(str);
appendedSoFar = str.length() + 1;
}
}
return output.toString();
public String populateTable(String[] strings, int charPerLine) {
StringBuilder output = new StringBuilder();
int appendedSoFar = 0;
for (String str : strings) {
int remaining = charPerLine - appendedSoFar;
if ((remaining - 2) >= str.length()) {
// Beginning of the line.
if(remaining != charPerLine) {
output.append(" ");
}
output.append(str);
appendedSoFar += str.length() + 1;
} else {
output.append("|");
output.append("\n");
output.append(str);
appendedSoFar = str.length() + 1;
}
}
return output.toString();
}
- Anonymous November 19, 2022