1. Iterative Word Buffer Accumulation
Intuition
Maintain currentLine buffer. Iterate through words: if adding word exceeds maxWidth, format currentLine, add to result, and start new line. Format remaining words as the last left-justified line.
When to apply: Basic baseline comparison.
Algorithm
- Initialize
res = [],line = [],lineChars = 0. - For
wordinwords: - If
lineChars + word.length + line.length > maxWidth: - Format
linewith spaces and push tores. - Reset
line = [],lineChars = 0. -
line.push(word); lineChars += word.length. - Format last
line(left-justified) and push tores. - Return
res.
#include <iostream>#include <string>#include <vector> class Solution {public: std::vector<std::string> fullJustify(std::vector<std::string>& words, int maxWidth) { std::vector<std::string> res; int i = 0, n = words.size(); while (i < n) { int j = i, lineLen = 0; while (j < n && lineLen + (int)words[j].size() + (j - i) <= maxWidth) { lineLen += words[j].size(); j++; } std::string line = ""; int numWords = j - i; int totalSpaces = maxWidth - lineLen; // Last line or single-word line -> left justify if (j == n || numWords == 1) { for (int k = i; k < j; ++k) { line += words[k]; if (k < j - 1) line += " "; } while ((int)line.size() < maxWidth) line += " "; } else { int baseSpaces = totalSpaces / (numWords - 1); int extraSpaces = totalSpaces % (numWords - 1); for (int k = i; k < j - 1; ++k) { line += words[k]; int spaces = baseSpaces + (k - i < extraSpaces ? 1 : 0); line.append(spaces, ' '); } line += words[j - 1]; } res.push_back(line); i = j; } return res; }}; int main() { Solution sol; std::vector<std::string> words = {"This", "is", "an", "example", "of", "text", "justification."}; auto ans = sol.fullJustify(words, 16); for (const auto& line : ans) std::cout << '"' << line << '"' << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(Total Characters)— Every character and space is created and appended in linear time. - Space complexity:
O(Total Characters)
Why Brute Force Doesn't Scale:
Two-pointer slice evaluation in O(N) total character complexity.
Exact string pre-allocation (reserve(maxWidth)).