I found the error. It is in the case of left-justifying the last line. My available spaces are getting to negative, and I'm getting stuck there until memory exhausts.
updated portion of the code:
if(isLastLine){
for(String word: mapping.words){
sb.append(word);
currentWordCount++;
if(currentWordCount < wordcount){
sb.append(" ");
}
}
int remaining = availableSpaces - minSpaces;
while(remaining > 0){
sb.append(" ");
remaining -= 1;
}
}