Skip to main content
Back to problems
#68
Hard Algorithms

Text justification

Array String Simulation
50.5% acceptance
Jan 12, 2026
4514
5362
Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. Note: A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn full_justify(words: Vec<String>, max_width: i32) -> Vec<String> {
    let max_width = max_width as usize;
    let mut result = Vec::new();
    let mut i = 0;
    
    while i < words.len() {
      let mut line = vec![words[i].clone()];
      let mut line_len = words[i].len();
      i += 1;
      
      // Try to add more words to current line
      while i < words.len() && line_len + 1 + words[i].len() <= max_width {
        line.push(words[i].clone());
        line_len += 1 + words[i].len();
        i += 1;
      }
      
      // Build the line
      let is_last_line = i == words.len();
      let line_str = if is_last_line || line.len() == 1 {
        // Left justify
        let mut s = line.join(" ");
        s.push_str(&" ".repeat(max_width - s.len()));
        s
      } else {
        // Full justify
        let total_chars: usize = line.iter().map(|w| w.len()).sum();
        let total_spaces = max_width - total_chars;
        let gaps = line.len() - 1;
        let spaces_per_gap = total_spaces / gaps;
        let extra_spaces = total_spaces % gaps;
        
        let mut s = String::new();
        for (idx, word) in line.iter().enumerate() {
          s.push_str(word);
          if idx < line.len() - 1 {
            s.push_str(&" ".repeat(spaces_per_gap));
            if idx < extra_spaces {
              s.push(' ');
            }
          }
        }
        s
      };
      
      result.push(line_str);
    }
    
    result
  }
}