#2468
Split Message Based on Limit
HardStringEnumerationEnumerationString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach involves calculating the total number of digits in the total parts and using that to determine how to split the message efficiently. This reduces unnecessary iterations and checks.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the maximum number of parts possible based on the limit and the maximum suffix length.
- 2Step 2: Iterate through possible total part counts, calculating the suffix length dynamically.
- 3Step 3: For each total part count, check if the message can be split into valid parts and format them with the appropriate suffix.
- 4Step 4: Return the first valid split found.
solution.py22 lines
1def splitMessage(message, limit):
2 n = len(message)
3 max_parts = 1
4 while len(f'<{max_parts}/{max_parts}>') <= limit:
5 max_parts += 1
6 max_parts -= 1
7 for total_parts in range(1, max_parts + 1):
8 suffix_length = len(f'<{total_parts}/{total_parts}>')
9 max_part_length = limit - suffix_length
10 if max_part_length <= 0:
11 continue
12 parts = []
13 index = 0
14 for i in range(total_parts):
15 part = message[index:index + max_part_length]
16 if len(part) == 0:
17 break
18 parts.append(part + f'<{i + 1}/{total_parts}>')
19 index += max_part_length
20 if ''.join(p[:-suffix_length] for p in parts) == message:
21 return parts
22 return []ℹ
Complexity note: The time complexity is O(n) because we only iterate through the message a limited number of times based on the maximum possible parts, which is much more efficient than the brute-force method.
- 1Understanding the suffix length is crucial for determining how to split the message.
- 2Iterating through possible part counts efficiently can help avoid unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.