HardNo. 2468
Split Message Based on Limit — LeetCode 2468 Python Solution
- Pattern
- Monotonic Stack
- Topics
- String, Binary Search, Enumeration
- Reading time
- 3 min
- Source
- leetcode.com
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
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
- Time
- O(n × log n)where n is the length of the string `message`
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0902 | Numbers At Most N Given Digit Set | Hard |
| 1268 | Search Suggestions System | Medium |
| 2055 | Plates Between Candles | Medium |
| 2476 | Closest Nodes Queries in a Binary Search Tree | Medium |
| 0004 | Median of Two Sorted Arrays | Hard |
| 0033 | Search in Rotated Sorted Array | Medium |
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 × 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.