Implement text formatter and sum subarray products
Company: Pika
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates algorithmic problem-solving and implementation skills across string formatting (line breaking and space management) and array-based combinatorial computation (sum of subarray products), emphasizing correctness, edge-case handling, and analysis of time and space complexity.
Left-Justified Text Formatter
Constraints
- 1 <= maxWidth <= 1000
- 0 <= number of words <= 10^4
- 1 <= len(word) <= maxWidth for every word (no word is longer than the line width)
- Words contain non-space printable characters
Examples
Input: (["This", "is", "an", "example", "of", "text", "justification."], 16)
Expected Output: ["This is an ", "example of text ", "justification. "]
Explanation: "This is an" (10 chars) fits; adding "example" would need 18 > 16, so it starts line 2. "example of text" is 15 chars; "justification." would push it over 16. Each line is padded with trailing spaces to width 16.
Input: ([], 5)
Expected Output: []
Explanation: No words yields no lines.
Hints
- Greedily pack words: keep adding the next word to the current line while the running length plus one space plus the next word still fits within maxWidth.
- Join the chosen words with single spaces, then append (maxWidth - currentLength) trailing spaces so every line is exactly maxWidth characters.
- Because every line (including the last) is left-justified with the same padding rule, you do not need a special case for the final line.
Sum of All Subarray Products
Constraints
- 0 <= n <= 10^5
- items[k] may be negative, zero, or positive
- The final sum fits in a 64-bit signed integer for the given limits (use long / long long in Java / C++)
Examples
Input: ([1, 2, 3],)
Expected Output: 20
Explanation: Subarrays: [1]=1, [2]=2, [3]=3, [1,2]=2, [2,3]=6, [1,2,3]=6; total 20.
Input: ([2, 3],)
Expected Output: 11
Explanation: [2]=2, [3]=3, [2,3]=6; total 11.
Hints
- Let suffix(i) be the sum of products of all subarrays that START at index i. Then suffix(i) = items[i] * (1 + suffix(i+1)): items[i] alone contributes items[i]*1, and extending each subarray starting at i+1 by items[i] contributes items[i]*suffix(i+1).
- Process the array from right to left, maintaining a single 'running' value equal to suffix(i), and add it to the total at each step. This gives an O(n) one-pass solution.
- Be careful with zeros (a subarray containing a zero contributes 0) and negatives (products can flip sign) — the recurrence handles both automatically; no special-casing is needed.