π Prepare Notification Message with Length Limit in Python
π Problem Overview
You're building a notification system where messages are shown on a mobile screen. The message must not exceed K
characters, and it must be cropped properly if itβs too long β meaning only whole words are kept, and an ellipsis ("...") is added when cropping occurs.
β¨ Cropping Rules
Given:
message
: a space-separated string.K
: the character limit for the notification.
Produce:
- A string of at most
K
characters that: - Ends with
" ..."
if cropped (note: a space before the three dots). - Is as long as possible without breaking words.
- If the whole message fits, return it as is.
- If no word fits, return only
"..."
(3 dots, no space before).
β
Examples
MessageKOutput"And now here is my secret"
15"And now ...""There is an animal with four legs"
15"There is an ...""super dog"
4"...""how are you"
20"how are you"
π§ Algorithm Breakdown
- Check edge case: If
K < 3
, return "..."
right away. - Split the message into words.
- Build the message one word at a time, stopping when adding another word would exceed the limit.
- If cropping was necessary, check if there's room for
" ..."
and add it properly. - If no word fits, return only
"..."
.
π§βπ» Python Implementation
python
def solution(message, K):
if K < 3:
return "..."
words = message.split()
notification = ""
for word in words:
if notification:
# Check space + word
if len(notification) + len(word) + 1 <= K:
notification += " " + word
else:
break
else:
# First word (no leading space)
if len(word) <= K:
notification = word
else:
break
# Full message fits
if len(notification) == len(message):
return notification
# If no words fit
if not notification:
return "..."
# Ensure we can add " ..."
if len(notification) + 4 <= K:
return notification + " ..."
else:
# Edge case: crop an extra word if needed to fit the ellipsis
words = notification.split()
trimmed = ""
for word in words[:-1]:
if not trimmed:
test = word
else:
test = trimmed + " " + word
if len(test) + 4 <= K:
trimmed = test
else:
break
return trimmed + " ..." if trimmed else "..."
π Important Notes
" ..."
is 4 characters including the space.- The logic handles the corner case where no word fits within the limit.
- This is a greedy solution β it adds as many full words as possible from the beginning.
π§ͺ Test It!
python
print(solution("And now here is my secret", 15)) # "And now ..."
print(solution("There is an animal with four legs", 15)) # "There is an ..."
print(solution("super dog", 4)) # "..."
print(solution("how are you", 20)) # "how are you"