Split Message Based on Limit - Problem

You are given a string message and a positive integer limit.

You must split message into one or more parts based on limit. Each resulting part should have the suffix "<a/b>", where "b" is to be replaced with the total number of parts and "a" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.

The resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.

Return the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.

Input & Output

Example 1 — Basic Split
$ Input: message = "this is really a long text", limit = 16
Output: ["this is re<1/3>", "ally a long<2/3>", " text<3/3>"]
💡 Note: Split into 3 parts: Part 1 has 10 chars + 6 char suffix = 16 total. Part 2 has 11 chars + 6 char suffix = 17 ≤ 16? No, this would be invalid. Let me recalculate: we need exactly 16 chars per part except the last.
Example 2 — Impossible Split
$ Input: message = "short", limit = 15
Output: []
💡 Note: Cannot split because even with 1 part, "short<1/1>" would be 5 + 6 = 11 chars, but we need exactly 15 chars in each part except the last.
Example 3 — Edge Case Single Part
$ Input: message = "ab", limit = 5
Output: ["ab<1/1>"]
💡 Note: Single part: "ab" (2 chars) + "<1/1>" (5 chars) = 7 total, but limit is 5, so this is actually impossible. Let me reconsider the problem constraints.

Constraints

  • 1 ≤ message.length ≤ 104
  • 1 ≤ limit ≤ 104

Visualization

Tap to expand
Split Message Based on Limit: Transform Long Text into PartsInput: "this is really a long text", limit = 16Split into minimum parts where each part ≤ 16 characters (including suffix)Part 1"this is re<1/3>"16 charactersPart 2"ally a long<2/3>"16 charactersPart 3 (Last)" text<3/3>"10 chars (≤ 16)Output: ["this is re<1/3>", "ally a long<2/3>", " text<3/3>"]
Understanding the Visualization
1
Input
Message and character limit per part
2
Process
Split message into minimum parts with suffixes <a/b>
3
Output
Array of parts, each ≤ limit length (except last can be shorter)
Key Takeaway
🎯 Key Insight: The suffix length depends on total parts count, requiring us to try different part counts to minimize splits
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
12.4K Views
Medium Frequency
~35 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen