Split Message Based on Limit — LeetCode 2468 Python Solution

HardStringBinary SearchEnumeration
Problem
#2468
Reading time
3 min

The problem

You are given a string, message, and a positive integer, limit. You must split message into one or more parts based on limit.

Example

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>","es<12/14>","sa<13/14>","ge<14/14>"]
Explanation
The first 9 parts take 3 characters each from the beginning of message.

Python solution

Python
class Solution:
    def splitMessage(self, message: str, limit: int) -> List[str]:
        n = len(message)
        sa = 0
        for k in range(1, n + 1):
            sa += len(str(k))
            sb = len(str(k)) * k
            sc = 3 * k
            if limit * k - (sa + sb + sc) >= n:
                ans = []
                i = 0
                for j in range(1, k + 1):
                    tail = f'<{j}/{k}>'
                    t = message[i : i + limit - len(tail)] + tail
                    ans.append(t)
                    i += limit - len(tail)
                return ans
        return []

Complexity

MeasureComplexity
TimeO(n\times \log n), where n is the length of the string `message`
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2468. Split Message Based on Limit is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2468. Split Message Based on Limit?
LeetCode 2468. Split Message Based on Limit is rated Hard on LeetCode.
What is the time complexity of LeetCode 2468. Split Message Based on Limit?
The Python solution on this page runs in O(n\times \log n), where n is the length of the string `message`.
What is the space complexity of LeetCode 2468. Split Message Based on Limit?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2468. Split Message Based on Limit cover?
LeetCode 2468. Split Message Based on Limit is tagged String, Binary Search and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview