Query-Driven Text Wrapper with Last-Line Balancing
StringsAuto-graded · 20 test casesLast updated
Parse a URL query string by hand, then greedily wrap the text to a width and fix a lone last-line word by borrowing from the previous line.
Query-Driven Text Wrapper
A rendering service receives a URL whose query string says which text to display and how wide each line may be. Write a function that reads these settings from the URL and returns the text broken into lines.
Step 1: Read the query string
- The query string is everything after the first
?in the URL. If the URL has no?, there are no parameters. - Parameters are separated by
&. Skip empty pieces (for example, from&&). - Split each piece at its first
=into a key and a value. Any further=characters belong to the value. A piece with no=has the whole piece as its key and an empty string as its value. - In each value (not in keys), replace every
+and every%20with a single space. No other percent-escapes are decoded, and no URL-parsing library may be used. - If the same key appears several times, the last occurrence wins.
Two parameters matter:
text: the string to wrap. If it is missing or empty, return[].width: the maximum line length. Parse the (decoded) value as a base-10 integer, ignoring surrounding whitespace the way Python'sint()does. If it is missing, not a valid integer, or not greater than zero, use20.
Step 2: Greedy wrapping
- Split
texton whitespace into words. Runs of whitespace count as one separator. If this gives no words (the text was only whitespace), return[]. - Build lines from left to right. Put each word on the current line if the line, with one space between words, would still have length at most
width. Otherwise, close the current line and start a new one with that word. - Punctuation stuck to a word is part of that word.
- Lines are the words joined by exactly one space.
Step 3: Last-line balancing
After wrapping, if there is more than one line and the last line holds exactly one word, try to move one word down to it:
- Take the last word of the second-to-last line and put it in front of the lone last word.
- Do this only if the second-to-last line had at least 2 words before the move, and the new last line (the moved word, a space, then the old last word) has length at most
width. - Otherwise leave the lines unchanged.
- Apply this adjustment at most once. Do not re-check earlier lines afterwards, even if the move leaves a one-word line behind.
Function
Implement wrap_query_text(url), which returns the list of lines.
Constraints
1 <= len(url) <= 10005 <= width <= 100whenever a valid width is supplied- Every word is no longer than
width - Do not use
urllib.parseor any other URL-parsing library
Examples
Example 1
Input: wrap_query_text('https://airbnb.com/search?text=Cozy+cabin+in+the+woods&width=10')
Output: ['Cozy cabin', 'in', 'the woods']
Example 2
Input: wrap_query_text('https://airbnb.com/rooms?text=Quiet%20loft&width=20')
Output: ['Quiet loft']
Hints
Hint 1
Handle the two jobs separately: first turn the URL into a dictionary of parameters, then work only with the resulting text and width.
Hint 2
Split each parameter on the first '=' only (split('=', 1)). Decode '+' and '%20' in values only, and let later duplicate keys overwrite earlier ones. Remember the fallbacks: width defaults to 20, and missing, empty, or whitespace-only text gives [].
Hint 3
Pack words greedily while tracking the current line length (adding 1 for the space). After packing, run a single check on the last two lines for the lone-word case, and only move the word if the new last line still fits in width.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two independent stages, so solve them one after the other.
1. Parse the query string.
- Find the first
?. If there is none, there are no parameters, sotextis missing and the answer is[]. - Split the rest on
&and skip empty pieces. - Split each piece with
split('=', 1). A value that contains=keeps everything after the first=, and a piece without=gets an empty value. - Replace
+and%20with a space in the value, then store it in a dictionary. Later duplicates overwrite earlier ones. - Read
widthwithint(...)inside atry. Missing, non-numeric, or non-positive values fall back to20. Because+becomes a space before parsing, a value like+12still parses as12. - If
textis missing, empty, or has no words aftersplit(), return[].
2. Greedy wrapping. Keep the words of the current line and its rendered length. For each word:
- If the line is empty, add the word.
- Otherwise, compute
current_length + 1 + len(word). If it exceedswidth, close the line and start a new one with this word. If not, append the word.
3. Last-line balancing.
Only after wrapping, if there are at least two lines, the last line has one word, and the previous line has at least two words, form moved + ' ' + last_word. If its length is at most width, move that word down. This is done exactly once.
Why it is correct
- A line is closed only when the next word would not fit, and every added word kept the length within
width. So each greedy line is valid and as full as possible in reading order. - The balancing step keeps both touched lines valid. The previous line only gets shorter and still has at least one word. The new last line is explicitly checked against
width. Word order never changes. - Joining with
' 'guarantees single spaces in the output, even when the input has runs of encoded spaces. - Doing the balancing as a separate post-step matches the rule, which concerns only the final two lines and is applied once.
Complexity
- Time: O(n), where n is
len(url). Parsing, replacement, splitting, and packing are each linear, and balancing touches only two lines. - Space: O(n) for the parameter dictionary, the word list, and the output.
Reference solution
from typing import List
def wrap_query_text(url: str) -> List[str]:
# Parse the query string manually.
params = {}
question = url.find('?')
if question >= 0:
query = url[question + 1:]
for part in query.split('&'):
if not part:
continue
if '=' in part:
key, value = part.split('=', 1)
else:
key, value = part, ''
value = value.replace('+', ' ')
value = value.replace('%20', ' ')
params[key] = value
text = params.get('text', '')
if not text:
return []
width_text = params.get('width', '')
try:
width = int(width_text)
if width <= 0:
width = 20
except (TypeError, ValueError):
width = 20
words = text.split()
if not words:
return []
# Greedy packing.
lines = []
current = []
current_length = 0
for word in words:
added_length = len(word) if not current else current_length + 1 + len(word)
if current and added_length > width:
lines.append(' '.join(current))
current = [word]
current_length = len(word)
else:
current.append(word)
current_length = added_length
if current:
lines.append(' '.join(current))
# Last-line balancing (applied once).
if len(lines) > 1:
last_words = lines[-1].split()
previous_words = lines[-2].split()
if len(last_words) == 1 and len(previous_words) >= 2:
moved = previous_words[-1]
new_last = moved + ' ' + last_words[0]
if len(new_last) <= width:
lines[-2] = ' '.join(previous_words[:-1])
lines[-1] = new_last
return lines