Text Formatting and Dynamic Schedule Tracker
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Perform greedy text wrapping to fixed line widths alongside dynamic interval point queries with insertion and removal.
Write a function that processes two independent tasks given as a single workload: a greedy word-formatting operation and a sequence of dynamic schedule operations.
Task 1: Word Wrapping
Format a list of strings (words) into formatted lines such that:
- Words appear in the same order as in
words. - Adjacent words on the same line are separated by exactly one space character.
- A line cannot exceed length
w, unless a single word itself is longer thanw(in which case it occupies its own line without being broken up). - Each line contains as many words as possible greedily. A new line is started only when adding the next word would cause the line's total length (including separating spaces) to exceed
w.
Task 2: Dynamic Schedule Active Count
Process a list of operations that modify or query an active schedule of intervals marked by unique entity identifiers. The dynamic system tracks active time ranges [start, end] (inclusive).
Operations are represented as lists with one of the following formats:
["add", entity_id, start, end]: Registers an interval[start, end]forentity_id. Ifentity_idalready exists, its previous interval is overwritten. Ifstart > end, the interval is registered but covers zero time points.["remove", entity_id]: Deletesentity_idand its associated interval. Ifentity_iddoes not exist, this operation is ignored.["get_active_count", time]: Queries how many currently registered entities have an interval[start, end]such thatstart <= time <= end.
The function must return a dictionary containing two keys:
"lines": A list of strings corresponding to the wrapped text lines."counts": A list of integers containing the results of each"get_active_count"query in the order they appear inoperations.
Constraints
- $0 \le \text{len}(words) \le 10^4$
- $1 \le w \le 10^5$
- Words contain alphanumeric non-space characters.
- $0 \le \text{len}(operations) \le 10^4$
start,end, and querytimevalues are integers within range $[-10^9, 10^9]$.entity_idvalues are arbitrary strings or integers.- Empty lists within
operations(e.g.[]) should be safely ignored.
Output Format
Return a dictionary of the form:
{"lines": List[str], "counts": List[int]}
Examples
Example 1
Input: wrap_text_and_waitlist(['hello', 'world', 'this', 'is', 'a', 'test'], 10, [['add', 'A', 1, 5], ['add', 'B', 3, 7], ['get_active_count', 4], ['get_active_count', 6], ['remove', 'A'], ['get_active_count', 4]])
Output: {'lines': ['hello', 'world this', 'is a test'], 'counts': [2, 1, 1]}
Example 2
Input: wrap_text_and_waitlist(['one', 'two', 'three', 'four'], 7, [])
Output: {'lines': ['one two', 'three', 'four'], 'counts': []}
Example 3
Input: wrap_text_and_waitlist([], 10, [['get_active_count', 0], ['add', 'x', -2, 2], ['get_active_count', -2], ['get_active_count', 2], ['get_active_count', 3]])
Output: {'lines': [], 'counts': [0, 1, 1, 0]}
Hints
Hint 1
For Task 1, track the total width of the current line including spaces. Add a word if it fits; otherwise, push the current line to your output list and start a new line.
Hint 2
For Task 2, notice all query times and interval endpoints are known ahead of time. Use coordinate compression to map discrete time points to array indices.
Hint 3
Use a Fenwick tree (Binary Indexed Tree) or segment tree over the compressed coordinates to efficiently support range updates (+1 on interval add, -1 on removal) and point queries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem consists of two independent parts combined into one interface:
Part 1: Greedy Word Wrapping
We iterate over the list of words while keeping track of the current line's words and accumulated string length (including space separators).
- For each word, calculate the length required if appended to the current line:
len(word)if the current line is empty, orcurrent_length + 1 + len(word)if non-empty. - If the current line is non-empty and adding the word exceeds width
w, output the joined current line, and start a new line containing just this word. - Otherwise, append the word to the current line.
- After processing all words, output any remaining line.
Part 2: Dynamic Interval Active Count (Difference Array + Coordinate Compression + BIT)
Each interval update [start, end] adds $+1$ to all points in the range. An interval query at time $t$ asks for the point sum at $t$.
- Coordinate Compression: Because coordinates can be large (up to $10^9$ or negative), extract all
start,end, and querytimevalues from operations, sort them, and remove duplicates. - Difference Array via Fenwick Tree (BIT):
- An interval addition
[start, end]corresponds to $+1$ at indexbisect_left(start)and $-1$ at indexbisect_right(end). - A query at time $t$ is equivalent to taking the prefix sum of the difference array up to
bisect_right(t). - Operations are processed sequentially, storing current entity intervals in a hash map to support overwriting and removal.
- An interval addition
Complexity
- Text Wrapping: $\mathcal{O}(N)$ where $N$ is total number of characters across all words.
- Schedule Tracker: $\mathcal{O}(M \log M)$ time where $M$ is the number of operations, due to coordinate sorting and $\mathcal{O}(\log M)$ Fenwick tree operations per update/query.
- Space Complexity: $\mathcal{O}(N + M)$ to store output lines, compressed coordinates, and the Fenwick tree.
from bisect import bisect_left, bisect_right
from typing import List, Dict
def wrap_text_and_waitlist(words: List[str], w: int, operations: List[List]) -> Dict[str, object]:
lines = []
current_line = []
current_length = 0
for word in words:
needed = len(word) if not current_line else current_length + 1 + len(word)
if current_line and needed > w:
lines.append(" ".join(current_line))
current_line = [word]
current_length = len(word)
else:
current_line.append(word)
current_length = needed
if current_line:
lines.append(" ".join(current_line))
coordinates = []
for op in operations:
if not op:
continue
kind = op[0]
if kind == "add":
coordinates.extend([op[2], op[3]])
elif kind == "get_active_count":
coordinates.append(op[1])
coordinates = sorted(set(coordinates))
size = len(coordinates)
bit = [0] * (size + 2)
def update(idx: int, val: int):
while idx <= size:
bit[idx] += val
idx += idx & -idx
def query(idx: int) -> int:
total = 0
while idx > 0:
total += bit[idx]
idx -= idx & -idx
return total
def apply_interval(start: int, end: int, val: int):
if start > end or not coordinates:
return
left = bisect_left(coordinates, start) + 1
right = bisect_right(coordinates, end) + 1
update(left, val)
if right <= size:
update(right, -val)
active_entities = {}
counts = []
for op in operations:
if not op:
continue
kind = op[0]
if kind == "add":
entity_id, start, end = op[1], op[2], op[3]
if entity_id in active_entities:
old_start, old_end = active_entities[entity_id]
apply_interval(old_start, old_end, -1)
active_entities[entity_id] = (start, end)
apply_interval(start, end, 1)
elif kind == "remove":
entity_id = op[1]
if entity_id in active_entities:
start, end = active_entities.pop(entity_id)
apply_interval(start, end, -1)
elif kind == "get_active_count":
t = op[1]
idx = bisect_right(coordinates, t)
counts.append(query(idx))
return {"lines": lines, "counts": counts}