Coding questions · TikTok
Segment a message with width-constrained suffixes
This question evaluates algorithm design and string-processing skills, focusing on constraint-aware segmentation with variable-length suffix metadata and the accompanying complexity analysis.
Given a message string s and an integer width W, split s into consecutive segments and append a suffix "i/n" to each segment indicating its 1-indexed position i out of the total n segments. Part A (suffix excluded from width): Split s into chunks of up to W characters (not counting the suffix), then append the suffix to each line; return the list of lines. Part B (suffix included in width): Now len(chunk) + len(suffix(i,n)) must be ≤ W for every line, but n is unknown in advance because the suffix length depends on n. Produce valid lines that cover the entire message in order (breaking anywhere is allowed; no reordering). If impossible (e.g., W < len("1/1")), return an error. Implement an efficient algorithm to determine n and the segmentation and analyze its complexity.
Segment Message with Suffix Excluded from Width
Split a message into chunks of at most W characters, then append i/n to each chunk.
Constraints
- W counts only message characters in this part
Examples
Example 1
Input: ('abcdefghij', 4)
Output: ['abcd1/3', 'efgh2/3', 'ij3/3']
Explanation: Three chunks before suffixes.
Example 2
Input: ('', 5)
Output: ['1/1']
Explanation: Empty message still produces one empty segment with suffix.
Hints
- n is known after chunking by W.
Segment Message with Suffix Included in Width
Split a message so every segment plus its i/n suffix has length at most W, choosing the smallest feasible n.
Constraints
- Breaking anywhere is allowed
- Return [] when impossible
Examples
Example 1
Input: ('abcdefghij', 6)
Output: ['abc1/4', 'def2/4', 'ghi3/4', 'j4/4']
Explanation: Suffix consumes part of width.
Example 2
Input: ('abc', 3)
Output: []
Explanation: Only one-character payload fits with 1/3 suffixes.
Hints
- Try increasing n until total payload capacity reaches the message length.