Split Message Based on Limit - Problem
Message Pagination Problem: You need to split a message into multiple parts where each part includes pagination information in the format
Given a
Return the array of paginated parts, or an empty array if impossible.
<a/b>.Given a
message string and a positive integer limit, you must:- Split the message into one or more parts
- Each part must have suffix
<a/b>wherebis total parts andais the current part number (1-indexed) - Each part's total length (including suffix) must be exactly
limit, except the last part which can be โคlimit - When suffixes are removed and parts concatenated, they should equal the original message
- Minimize the total number of parts
Return the array of paginated parts, or an empty array if impossible.
Input & Output
example_1.py โ Basic Split
$
Input:
message = "this is really a very awesome message", limit = 9
โบ
Output:
["thi<1/14>", "s i<2/14>", "s r<3/14>", "eal<4/14>", "ly <5/14>", "a v<6/14>", "ery<7/14>", " aw<8/14>", "eso<9/14>", "me<10/14>", " m<11/14>", "ess<12/14>", "ag<13/14>", "e<14/14>"]
๐ก Note:
With limit=9, each part can hold at most 9 characters including the suffix. The suffix "<10/14>" takes 7 chars, leaving 2 chars for content in parts 10-14. The algorithm finds that 14 parts is the minimum needed.
example_2.py โ Impossible Case
$
Input:
message = "short message", limit = 15
โบ
Output:
[]
๐ก Note:
Even with 1 part, "short message<1/1>" would be 19 characters, exceeding the limit of 15. Since it's impossible to fit the message with any number of parts, return empty array.
example_3.py โ Single Part
$
Input:
message = "hello", limit = 12
โบ
Output:
["hello<1/1>"]
๐ก Note:
The entire message "hello" plus suffix "<1/1>" equals "hello<1/1>" with length 10, which fits within limit 12. Only one part is needed.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Space
For each candidate part count, calculate how much space suffixes will take
2
Check Feasibility
Verify if remaining space can accommodate the entire message
3
Binary Search
Use binary search to efficiently find the minimum feasible part count
4
Generate Result
Split the message using the optimal part count
Key Takeaway
๐ฏ Key Insight: Binary search works because if we can split into k parts, we can usually split into k+1 parts too (monotonic property). The challenge is calculating space efficiently for each candidate part count.
Time & Space Complexity
Time Complexity
O(nยฒ)
We try up to n different part counts, and for each we simulate the splitting process which takes O(n) time
โ Quadratic Growth
Space Complexity
O(n)
Space needed to store the result array and temporary calculations
โก Linearithmic Space
Constraints
- 1 โค message.length โค 104
- 1 โค limit โค 104
- message consists only of lowercase English letters and spaces
- 1 โค limit โค 104
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code