Problem
Given a text message and max number of characters, implement how the phone company can represent a given message.
OR
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.
Examples
Example 1:
|
|
Example 2:
|
|
Similar problem
Solution
Method 1 - Brute force
The brute-force solution is appropriate for this problem because it systematically checks for the minimum number of parts needed to split the message within the provided constraints. Unlike binary search, which relies on properties like monotonicity to reduce the search space efficiently, brute-force directly simulates and checks each possible number of parts sequentially.
Example Demonstration: Why Binary Search Fails
Example taken from Przemyslaw. Consider the message "abbababbbaaa aabaa a"
with a character limit of 8
. Using brute force, the process is as follows:
- Attempt with 1 Part:
- Including the suffix
"<1/1>"
in the message, which is impossible because the suffix alone exceeds the character limit of8
.
- Including the suffix
- Attempt with 2 to 6 Parts:
- Similar reasoning: each attempt adds a suffix
"<a/b>"
, and these add up to exceed the limit or leave insufficient space in each part for the segments of the message.
- Similar reasoning: each attempt adds a suffix
- Attempt with 7 Parts:
- The added suffix
"<a/7>"
becomes progressively feasible as parts increase, but binary search might miss this oddity. - Parts created:
"abb<1/7>", "aba<2/7>", "bbb<3/7>", "aaa<4/7>", " a<5/7>", "ab<6/7>", "aa a<7/7>"
.
- The added suffix
- Why Binary Search Fails:
- Considering binary search property fails because parts succession isn’t strictly decreasing or increasing according to message length.
- For example, 10 parts fail the size check after further iteration and incorrectly suggest previous lower blocks, skipping valid configurations intermediates, inadvertently pushing towards other invalid parts.
Brute force approach
The brute-force method systematically verifies each number of parts, ensuring accuracy and reliability given the problem constraints.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the message. - 🧺 Space complexity:
O(n)
for storing the resulting parts.