Sentry.io OA New Grad 2023
Anonymous User
200
Aug 16, 2023
Aug 16, 2023
Hello!
I just took the Sentry.io new grad OA - it was a string manipulation problem about white spaces as shown below - I tried coding up a solution but I only resulted in TLE - I was wondering if anyone has an efficient approach on tackling this?
problem:
https://drive.google.com/file/d/1C0bW6B0PI9amfOJdJt7P8ywG-5u187bt/view?usp=sharing
my attempt (I was in the middle of trying to convert from using String to StringBuilder because I thought that was why it TLEed, however - after finishing it still wasn't enough)
public static List<String> add_whitespace(String words, int line_char_limit) {
String[] wordsArr = words.split("\\s+");
List<String> ans = new ArrayList<>();
List<String> wordsList = new ArrayList<>();
for (int i = 0; i < wordsArr.length; i++) {
if (wordsArr[i].equals("-")) {
if (i > 0 && i < wordsArr.length -1) {
wordsList.remove(i-1);
wordsList.add(wordsArr[i-1] + "-" + wordsArr[i+1]);
i++;
} else if (i == wordsArr.length -1) {
wordsList.remove(i-1);
wordsList.add(wordsArr[i-1] + "-" );
} else if (i==0) {
wordsList.add("-" );
}
} else {
wordsList.add(wordsArr[i]);
}
}
for (int i = 0; i < wordsList.size(); ) {
List<String> currLine = new ArrayList<>();
int charLen = 0;
String word = wordsList.get(i);
//System.out.println(word);
int j = i;
while (word.length() + charLen < line_char_limit) {
System.out.println(word);
currLine.add(word);
charLen += word.length();
j++;
word = wordsList.get(j);
}
i = j;
System.out.println(currLine);
int hyphenInd = word.indexOf("-");
if (hyphenInd != -1) {
wordsList.remove(j);
String prefix = word.substring(0, hyphenInd+1);
String suffix = word.substring(hyphenInd+1, word.length());
wordsList.add(j, suffix);
if (prefix.length() + charLen < line_char_limit) {
currLine.add(prefix);
} else {
wordsList.add(j, prefix);
}
}
if (currLine.size() == 1) {
int whiteCnt = line_char_limit - charLen;
int endRem = whiteCnt % 2;
int whiteEven = whiteCnt / 2;
StringBuilder whites = new StringBuilder();
for (int k = 0; k < whiteEven; k++) {
whites.append( " ");
}
StringBuilder result = new StringBuilder(whites.toString() + currLine.get(0) + whites.toString());
if (endRem != 0) {
result.append( " ");
}
ans.add(result.toString());
} else {
int whiteCnt = line_char_limit - charLen;
String whites = "";
if (currLine.size() == 2) {
for (int k = 0; k < whiteCnt; k++) {
whites += " ";
}
ans.add(currLine.get(0) + whites + currLine.get(1));
} else if (currLine.size() > 2) {
int whiteBetw = whiteCnt / (currLine.size()-1);
int whiteRem = whiteCnt % (currLine.size()-1);
String result = "";
for (int k = 0; k < whiteBetw; k++) {
whites += " ";
}
for (int k = 0; k < currLine.size()-1; k++) {
result += currLine.get(k) + whites;
}
System.out.println(currLine);
result += currLine.get(currLine.size()-1);
if (whiteRem != 0) {
result += " ";
}
ans.add(result);
}
}
}
return ans;
}
}Comments (1)

