Truncate Sentence: Split, Slice, and Join
LeetCode 1816, Truncate Sentence, gives you a sentence (a string of words separated by single spaces) and an integer k. Your job is to return the sentence truncated so that it contains only the first k words.
For example:
"Hello how are you Contestant"withk = 4returns"Hello how are you""What is the solution to this problem"withk = 4returns"What is the solution""chooseandchoose"withk = 1returns"chooseandchoose"
The approach: split, slice, join
This problem breaks down into three clean operations:
- Split the sentence on spaces to get an array of words.
- Slice the first
kelements from that array. - Join them back together with spaces.
That is the entire algorithm. The problem guarantees that k is always valid (between 1 and the number of words), so you do not need to worry about out-of-bounds cases.
Python makes this a one-liner thanks to str.split(), list slicing, and str.join(). But it is worth knowing the space-counting approach too, since it avoids creating an intermediate list.
The code
def truncate_sentence(s: str, k: int) -> str:
return " ".join(s.split()[:k])
Walk through what happens:
s.split()breaks the sentence into a list of words.[:k]takes only the firstkwords." ".join(...)glues them back together with spaces between them.
O(1) space approach: count spaces
If you want to avoid allocating an array of words, you can scan the string character by character and count spaces. The k-th space marks the boundary where you should cut.
def truncate_sentence(s: str, k: int) -> str:
count = 0
for i, ch in enumerate(s):
if ch == " ":
count += 1
if count == k:
return s[:i]
return s
Walk through what happens:
- Scan each character in the string.
- Every time you see a space, increment
count. - When
countreachesk, you have passed exactlykwords. Return everything before this space. - If you finish the loop without hitting
kspaces, the entire string haskor fewer words. Return it as-is.
This approach never builds a word list. It reads the string once and returns a slice of the original.
Visual walkthrough
Here is the split-slice-join approach running on "Hello how are you Contestant" with k = 4.
Step 1: Split the sentence into words
Splitting on spaces gives us an array of 5 words.
Step 2: Take the first k words
With k = 4, we slice the first four words from the array.
Step 3: Join with spaces
Joining the four words with spaces gives the final result.
The array goes from five words down to four, and joining them produces the truncated sentence.
Complexity analysis
| Approach | Time | Space |
|---|---|---|
| Split-slice-join | O(n), where n is the length of the string | O(n), for the word list |
| Space counting | O(n), where n is the length of the string | O(1), only a counter and index |
Both approaches scan the string once. The split-slice-join version is more readable, while the space-counting version avoids allocating extra memory. In an interview, either is fine. If the interviewer asks for a follow-up optimization, the space-counting version is the natural next step.
Building blocks
This problem uses two techniques that show up across many string problems.
String splitting
Breaking a string into tokens by a delimiter is one of the most common string operations. You will see it in sentence parsing, CSV processing, path manipulation, and anywhere you need to work with individual words or segments. The key idea is always the same: identify the separator, split on it, and work with the resulting pieces.
Space counting
Scanning a string and counting occurrences of a specific character lets you locate boundaries without building an intermediate data structure. This same technique applies to problems like counting words, finding the n-th occurrence of a delimiter, or locating sentence boundaries. It trades a bit of code clarity for better memory usage.
Edge cases
Single word. If the sentence is "hello" and k = 1, there are no spaces at all. The split approach returns ["hello"][:1], which joins to "hello". The space-counting approach finishes the loop without finding any spaces and returns the full string.
k equals the word count. If k matches the total number of words, you return the entire sentence unchanged. No truncation happens.
Long words. The sentence "aReallyLongWordHere short" with k = 1 returns just the first word. The length of individual words does not affect correctness, only the total string length affects runtime.
Two words. The sentence "a b" with k = 1 returns "a". The space-counting approach finds the space at index 1, increments count to 1, and since count == k, returns s[:1].
From understanding to recall
You can read through this solution and feel like you have it down. But two weeks from now, will you remember the one-liner? Will the space-counting approach come back to you when an interviewer asks for an O(1) space follow-up?
Spaced repetition bridges that gap. Instead of re-reading the full solution, you drill the individual building blocks (split-slice-join, space counting as a boundary finder) at increasing intervals. After a few reps spread across days, these patterns are locked in long-term memory. When you see a string manipulation problem in an interview, the pieces are already there.
Related posts
- Length of Last Word - Another easy string problem that works with words and spaces
- Find the Index of the First Occurrence in a String - String searching with character-by-character scanning
- Longest Common Prefix - Column-by-column string comparison across multiple inputs