Fixed-Width Line Packing and Subarray Product Sum

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Implement format_and_sum(words: List[str], max_width: int, items: List[int]) -> Dict[str, object], returning a dictionary {"lines": formatted_lines, "sum": subarray_product_sum} that combines two independent calculations:

  1. Fixed-width left-aligned line packing ("lines"):
    • Consume words in order without breaking any word across two rows, greedily placing as many whole words onto the current row as fit within max_width characters when consecutive words on the same row are separated by one ' ' character.
    • Format every output row—intermediate rows and the final row alike—by joining its words with single ' ' characters and appending trailing ' ' characters on the right until the row has exact length max_width.
    • If words is empty, "lines" is an empty list [].
  2. Contiguous slice product total ("sum"):
    • Over every non-empty contiguous slice items[left : right + 1] (0 <= left <= right < len(items)), multiply the integers inside that slice together, then sum those products across all len(items) * (len(items) + 1) // 2 slices.
    • If items is empty, "sum" is 0.

Examples

Example 1

Input:
words = ["Pack", "every", "word", "cleanly", "into", "fixed", "rows."]
max_width = 14
items = [2, 3, 4]

Output:
{
    "lines": [
        "Pack every    ",
        "word cleanly  ",
        "into fixed    ",
        "rows.         "
    ],
    "sum": 51
}

Walk-through: - "Pack every" uses 4 + 1 + 5 = 10 characters; "word" would require 10 + 1 + 4 = 15 > 14, so row 1 receives 4 trailing spaces. "word cleanly" (12 chars, 2 trailing spaces), "into fixed" (10 chars, 4 trailing spaces), and "rows." (5 chars, 9 trailing spaces) follow the same rule. - The contiguous slices of [2, 3, 4] have products 2, 3, 4, 2*3 = 6, 3*4 = 12, and 2*3*4 = 24, totaling 2 + 3 + 4 + 6 + 12 + 24 = 51.

Example 2

Input:
words = ["Ship", "fast", "diagnostics", "daily"]
max_width = 12
items = [3, -2, 2]

Output:
{
    "lines": [
        "Ship fast   ",
        "diagnostics ",
        "daily       "
    ],
    "sum": -19
}

Walk-through: - "Ship fast" (9 chars) cannot fit "diagnostics" (11 chars), so "diagnostics" occupies row 2 alone with 1 trailing space, and "daily" occupies row 3 with 7 trailing spaces. - The slice products of [3, -2, 2] are 3, -2, 2, -6, -4, and -12, summing to -19.

Example 3

Input:
words = ["Logs", "stay", "aligned", "under", "load"]
max_width = 13
items = [4, 0, -3, 2]

Output:
{
    "lines": [
        "Logs stay    ",
        "aligned under",
        "load         "
    ],
    "sum": -3
}

Walk-through: - "aligned under" measures 7 + 1 + 5 = 13 characters, matching max_width with zero trailing spaces. - Every slice spanning index 1 (0) has product 0; the remaining non-zero slices are [4] -> 4, [-3] -> -3, [-3, 2] -> -6, and [2] -> 2, giving 4 - 3 - 6 + 2 = -3.

Constraints

  • 1 <= max_width
  • 0 <= len(words) <= 10^5, and 1 <= len(word) <= max_width for every string in words (word contains no spaces).
  • 0 <= len(items) <= 10^5
  • -10^9 <= items[i] <= 10^9 (exact arbitrary-precision integer arithmetic is expected).

Step-by-step walkthrough

  1. Break the problem into two independent parts

    format_and_sum asks us to solve two separate tasks and return both answers inside one dictionary {"lines": ..., "sum": ...}:

    1. Text formatter: pack words into lines of width max_width without splitting any word, placing a single space between adjacent words and padding the right end with spaces so every line has length max_width.
    2. Sum of subarray products: given items, add up the product of every contiguous slice items[i..j] (0 <= i <= j < len(items)).

    Read the formatting rule closely before writing code:

    • Every non-final row uses one space between neighboring words, plus right-hand padding spaces to reach max_width.
    • The final row also joins neighboring words with one space and pads on the right with spaces to reach max_width.

    That means every line—including the last—follows the exact same formatting rule! And we pack each line greedily, fitting as many words onto the current line as max_width allows before starting a new line.

  2. Part 1: Pack words greedily onto each line

    Suppose the current line already holds line_words whose single-space-joined length is line_len, and the next word is word:

    • If line_words is empty, word starts the line and line_len becomes len(word).
    • If line_words is non-empty, placing word after the existing words needs one separating space plus len(word) characters, for a new length of line_len + 1 + len(word).
    • Whenever line_len + 1 + len(word) > max_width, word does not fit—so we pad and emit the current line, reset line_words, and start the next line with word.

    Here is how Example 1 (max_width = 14) packs ["Pack", "every", "word", "cleanly", "into", "fixed", "rows."]:

     ruler:  12345678901234 (width 14)
     line 1: "Pack every    "  <- "Pack"(4) + " " + "every"(5) = 10 chars;
                                  adding " " + "word"(4) would be 15 > 14, so pad 4 spaces.
     line 2: "word cleanly  "  <- 4 + 1 + 7 = 12 chars; pad 2 spaces.
     line 3: "into fixed    "  <- 4 + 1 + 5 = 10 chars; pad 4 spaces.
     line 4: "rows.         "  <- 5 chars; flushed after loop, pad 9 spaces.
    
    def pad_line(line_words: List[str], max_width: int) -> str:
        """Join words with single spaces and pad trailing spaces to reach max_width."""
        joined = " ".join(line_words)
        padding_spaces = max_width - len(joined)
        return joined + (" " * padding_spaces)
    
    
    def format_lines(words: List[str], max_width: int) -> List[str]:
        """Pack as many words as fit on each line, left-justified and padded to max_width."""
        lines: List[str] = []
        # line_words: words currently packed on the active line, e.g. ["Pack", "every"]
        line_words: List[str] = []
        # line_len: exact character count of " ".join(line_words) so fit checks are O(1)
        line_len = 0
    
        for word in words:
            # Adding `word` after existing words requires 1 separating space + len(word) chars.
            # Checking `if line_words` ensures the first word on a new line is always placed.
            if line_words and line_len + 1 + len(word) > max_width:
                lines.append(pad_line(line_words, max_width))
                line_words = []
                line_len = 0
    
            if line_words:
                line_len += 1 + len(word)
            else:
                line_len = len(word)
            line_words.append(word)
    
        # Flush the final non-empty line using the exact same single-space + right-pad rule.
        if line_words:
            lines.append(pad_line(line_words, max_width))
    
        return lines
    
  3. Part 2: Why brute-force subarray products is O(n^2)

    An array of length n has n * (n + 1) / 2 contiguous subarrays items[i..j]. Multiplying each subarray from scratch takes O(n^3) time; keeping a running product as j moves right for each start index i lowers that to O(n^2):

    def sum_subarray_products_quadratic(items: List[int]) -> int:
        total = 0
        for i in range(len(items)):
            product = 1
            for j in range(i, len(items)):
                product *= items[j]
                total += product
        return total
    

    Because there are O(n^2) subarrays in total, any approach that computes one subarray product at a time takes at least O(n^2) steps. To reach O(n) arithmetic steps, we need to fold many subarray products together at once.

  4. Key idea: group subarrays by their ending index

    Look at all contiguous subarrays of [a, b, c] grouped by where they end:

    End at index 0 (value a):
      [a]                    -> sum E[0] = a
    
    End at index 1 (value b):
      [b]                    -> b
      [a, b]                 -> a * b
      ------------------------------------------------
      sum E[1] = b + a*b = b * (1 + a) = b * (1 + E[0])
    
    End at index 2 (value c):
      [c]                    -> c
      [b, c]                 -> b * c
      [a, b, c]              -> a * b * c
      ------------------------------------------------
      sum E[2] = c + (b + a*b) * c = c * (1 + E[1])
    

    Why does this work at every index j with value x = items[j]? Every contiguous subarray ending at j is either:

    1. Just [x] alone, contributing x, or
    2. One of the subarrays ending at j - 1, extended by x. Extending multiplies each of their products by x. By the distributive law (p_1 * x + p_2 * x + ... = (p_1 + p_2 + ...) * x), their combined contribution is ending_sum * x.

    Adding the two pieces gives x + ending_sum * x = x * (1 + ending_sum).

    Notice how cleanly this handles tricky numbers:

    • Zeros (x = 0): ending_sum becomes 0 * (1 + ending_sum) = 0, wiping out every subarray reaching across the zero—just as multiplying by 0 should.
    • Negatives (x < 0): unlike Maximum Product Subarray (where multiplying by a negative swaps min and max), addition distributes over multiplication for positive and negative numbers alike ((-2) * (3 + (-5)) == (-2)*3 + (-2)*(-5)), so a single running variable ending_sum is completely exact!
    def sum_subarray_products(items: List[int]) -> int:
        """Compute the sum of products over all contiguous subarrays items[i..j]."""
        total_sum = 0
        # ending_sum: sum of products of all contiguous subarrays ending at the previous index
        ending_sum = 0
    
        for x in items:
            # Every subarray ending at `x` is either:
            #   1) [x] by itself (product = x), or
            #   2) a subarray ending one step earlier extended by `x` (sum of products = ending_sum * x).
            # By the distributive law: x + ending_sum * x = x * (1 + ending_sum).
            ending_sum = x * (1 + ending_sum)
            total_sum += ending_sum
    
        return total_sum
    
  5. Trace Example 2 on both parts

    Let's trace Example 2: words = ["Ship", "fast", "diagnostics", "daily"], max_width = 12, items = [3, -2, 2].

    First, sum_subarray_products([3, -2, 2]):

    Step  x   ending_sum = x * (1 + prev)     Subarrays ending here (products)         total_sum
    --------------------------------------------------------------------------------------------
    init  -   0                               none                                     0
    j=0   3   3 * (1 + 0)   =   3             [3] -> 3                                 3
    j=1  -2  -2 * (1 + 3)   =  -8             [-2] (-2), [3,-2] (-6) -> sum -8        -5
    j=2   2   2 * (1 + -8)  = -14             [2] (2), [-2,2] (-4), [3,-2,2] (-12)   -19
    

    And format_lines(words, 12):

    • "Ship" (4), "fast" (4+1+4=9) fit; "diagnostics" (9+1+11=21 > 12) starts a new line -> "Ship fast " (9 + 3 spaces).
    • "diagnostics" (11); "daily" (11+1+5=17 > 12) starts a new line -> "diagnostics " (11 + 1 space).
    • "daily" (5); loop ends, flush -> "daily " (5 + 7 spaces).

    Both outputs match {'lines': ['Ship fast ', 'diagnostics ', 'daily '], 'sum': -19}.

  6. Combine both helpers into `format_and_sum`

    Now the main function simply delegates to our two helpers and packages the result dictionary:

    def format_and_sum(words: List[str], max_width: int, items: List[int]) -> Dict[str, object]:
        formatted_lines = format_lines(words, max_width)
        subarray_product_sum = sum_subarray_products(items)
        return {"lines": formatted_lines, "sum": subarray_product_sum}
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def pad_line(line_words: List[str], max_width: int) -> str:
        """Join words with single spaces and pad trailing spaces to reach max_width."""
        joined = " ".join(line_words)
        padding_spaces = max_width - len(joined)
        return joined + (" " * padding_spaces)
    
    
    def format_lines(words: List[str], max_width: int) -> List[str]:
        """Pack as many words as fit on each line, left-justified and padded to max_width."""
        lines: List[str] = []
        # line_words: words currently packed on the active line, e.g. ["Pack", "every"]
        line_words: List[str] = []
        # line_len: exact character count of " ".join(line_words) so fit checks are O(1)
        line_len = 0
    
        for word in words:
            # Adding `word` after existing words requires 1 separating space + len(word) chars.
            # Checking `if line_words` ensures the first word on a new line is always placed.
            if line_words and line_len + 1 + len(word) > max_width:
                lines.append(pad_line(line_words, max_width))
                line_words = []
                line_len = 0
    
            if line_words:
                line_len += 1 + len(word)
            else:
                line_len = len(word)
            line_words.append(word)
    
        # Flush the final non-empty line using the exact same single-space + right-pad rule.
        if line_words:
            lines.append(pad_line(line_words, max_width))
    
        return lines
    
    
    def sum_subarray_products(items: List[int]) -> int:
        """Compute the sum of products over all contiguous subarrays items[i..j]."""
        total_sum = 0
        # ending_sum: sum of products of all contiguous subarrays ending at the previous index
        ending_sum = 0
    
        for x in items:
            # Every subarray ending at `x` is either:
            #   1) [x] by itself (product = x), or
            #   2) a subarray ending one step earlier extended by `x` (sum of products = ending_sum * x).
            # By the distributive law: x + ending_sum * x = x * (1 + ending_sum).
            ending_sum = x * (1 + ending_sum)
            total_sum += ending_sum
    
        return total_sum
    
    
    def format_and_sum(words: List[str], max_width: int, items: List[int]) -> Dict[str, object]:
        formatted_lines = format_lines(words, max_width)
        subarray_product_sum = sum_subarray_products(items)
        return {"lines": formatted_lines, "sum": subarray_product_sum}
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the two tasks with two everyday pictures. For the text formatter, imagine typing on an old fixed-width typewriter of width W: you type words separated by single spaces until the next word would cross the right margin, fill the rest of the current row with spaces, and hit carriage return—using a greedy algorithm, meaning an approach that makes the locally maximal choice (packing as many words as fit onto the current line) at each step without backtracking. For summing contiguous subarray products (slices of adjacent elements with no gaps), imagine rolling a snowball from left to right where ending_sum holds the combined sum of products of all subarrays ending at your current spot: stepping onto a new number x multiplies the entire snowball by x and adds x by itself, giving ending_sum = x * (1 + ending_sum).

The obvious nested-loop approach for subarray products computes all n * (n + 1) / 2 subarray products one by one, taking O(n^2) time instead of a single pass. Another tempting shortcut—dividing prefix products P[j + 1] / P[i]—crashes with division by zero as soon as 0 appears in items and loses precision if implemented with floating-point numbers. For the formatter, calling " ".join(...) repeatedly during trial checks wastes work compared to tracking the current line's character count in an integer line_len.

Let's trace both parts on a tiny example (words = ["Logs", "stay", "aligned"], max_width = 9, items = [2, 3, 4]):

  • Formatter: "Logs" sets line_len = 4; "stay" fits because 4 + 1 + 4 = 9 <= 9; "aligned" needs 9 + 1 + 7 = 17 > 9, so we emit "Logs stay" (0 trailing spaces) and start a new line with "aligned", which flushes as "aligned " (2 trailing spaces).
  • Subarray product sum: start with ending_sum = 0, total_sum = 0.
    • At x = 2: ending_sum = 2 * (1 + 0) = 2 ([2]), total_sum = 2.
    • At x = 3: ending_sum = 3 * (1 + 2) = 9 ([3] + [2, 3] = 3 + 6), total_sum = 11.
    • At x = 4: ending_sum = 4 * (1 + 9) = 40 ([4] + [3, 4] + [2, 3, 4] = 4 + 12 + 24), total_sum = 51.

Complexity

Let C be the total number of characters across all strings in words, L be the number of output lines, W = max_width, and n = len(items).

  • Formatter time: O(C + L * W). We inspect each word once, check whether it fits in O(1) using line_len, and build L padded lines of length W each, which is linear in the total size of the input and output strings.
  • Formatter space: O(L * W) for the output list (O(W) working space). Aside from the returned list of lines, line_words holds at most one line's worth of words at a time.
  • Subarray sum time: O(n) arithmetic operations. We loop through items once, performing one addition, one multiplication, and one accumulation per element. (In Python, arbitrary-precision integers can grow to O(n log M) bits when values have magnitude up to M, making big-integer multiplication O(n^2 log M) bit operations in the extreme case; with fixed-width integers or modular arithmetic, it is strictly O(n).)
  • Subarray sum space: O(1) extra space. Only two scalar variables (ending_sum and total_sum) are maintained.

Edge cases

  • Exact-width line (len(joined) == max_width): max_width - len(joined) is 0, so zero trailing spaces are appended.
  • max_width == 1: each 1-character word forms its own line with zero padding.
  • Every word on its own line: when len(word1) + 1 + len(word2) > max_width, each word is emitted and padded individually.
  • Empty words or empty items: words = [] cleanly returns lines = [] because if line_words: is false after the loop; items = [] skips the loop and returns sum = 0.
  • Zeros in items: when x == 0, ending_sum = 0 * (1 + ending_sum) = 0, naturally zeroing out every subarray spanning across the 0 while letting the next item start fresh.
  • Negative numbers in items: because the distributive property (x * (a + b) = x * a + x * b, meaning multiplying a sum equals summing the individual products) holds for negative numbers just like positive ones, signs flip accurately without tracking separate min/max variables.
  • Huge products: [10^9, 10^9, 10^9] reaches ~10^27, overflowing 64-bit integers in C++ or Java; Python int stays exact at arbitrary precision.

Common mistakes

  • Implementing full middle-space justification by habit: classic full justification spreads extra spaces across gaps between words on non-last lines, whereas this specification explicitly puts one space between adjacent words on every line and appends all padding spaces at the right end.
  • Forgetting the + 1 space in the fit check: writing line_len + len(word) <= max_width forgets the mandatory space between two words and produces lines of length max_width + 1.
  • Forgetting to flush the last line after the for loop: whatever remains in line_words when the loop finishes is the final line and must be padded and appended.
  • Writing ending_sum = x * ending_sum without 1 +: omitting 1 + leaves ending_sum stuck at 0 forever and misses every single-element subarray [x].
  • Using floating-point division on prefix products: fails on 0 and silently rounds integers beyond 2^53 (~9 * 10^15).

Alternative approaches

  • Zero-split segments with exact rational prefix products: splitting items at every 0 and maintaining prefix products with fractions.Fraction can also achieve O(n) arithmetic steps, but requires handling zero boundaries and greatest-common-divisor reductions—much heavier than the two-line x * (1 + ending_sum) recurrence.
  • Raggedness-minimizing line breaking: word processors such as TeX use dynamic programming (DP)—breaking a problem into overlapping subproblems and storing each subproblem's best answer—to minimize the sum of cubed trailing spaces across lines in O(k^2) time for k words, whereas interview text-formatting problems use greedy packing so as many words as possible fit on each line.

Follow-up questions

  • What would change in the line formatter if every line except the last had to distribute extra spaces evenly across gaps between words? Keep the exact same greedy loop to choose which words go on each line, and only change pad_line for non-last lines that contain k >= 2 words. With G = k - 1 gaps and S = max_width - sum(len(w) for w in line_words) total spaces to place, every gap receives S // G spaces and the leftmost S % G gaps each receive 1 extra space; single-word lines and the final line still use single spaces plus trailing right padding.
  • How would you return the subarray product sum modulo 10^9 + 7 when products can grow arbitrarily large or go negative? Apply modular arithmetic—taking remainders with % MOD (MOD = 10**9 + 7) after every addition and multiplication so numbers never exceed MOD - 1: ending_sum = (x * (1 + ending_sum)) % MOD and total_sum = (total_sum + ending_sum) % MOD. In Python, % with a positive MOD always maps negative values into [0, MOD - 1] automatically; in C++ or Java, normalize negative remainders with ((val % MOD) + MOD) % MOD.
  • If the word stream contained millions of words and could not fit in memory at once, how would you adapt the formatter? Turn format_lines into a Python generator (yield pad_line(...)) that consumes an iterator of words one word at a time. Because you only buffer line_words for the single line currently being built, peak memory drops from O(L * W) to O(W).

Follow-up questions

Similar questions

More Pika interview questions

All 2 Pika questions →