Skip to content
← All posts

Truncate Sentence: Split, Slice, and Join

4 min read
leetcodeproblemeasystrings

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" with k = 4 returns "Hello how are you"
  • "What is the solution to this problem" with k = 4 returns "What is the solution"
  • "chooseandchoose" with k = 1 returns "chooseandchoose"
word 1word 2word 3word 4word 5HellohowareyouContestantfirst k = 4 words (kept)keptdropped
The sentence "Hello how are you Contestant" with k = 4. The first four words are kept and the fifth is dropped.

The approach: split, slice, join

This problem breaks down into three clean operations:

  1. Split the sentence on spaces to get an array of words.
  2. Slice the first k elements from that array.
  3. 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:

  1. s.split() breaks the sentence into a list of words.
  2. [:k] takes only the first k words.
  3. " ".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:

  1. Scan each character in the string.
  2. Every time you see a space, increment count.
  3. When count reaches k, you have passed exactly k words. Return everything before this space.
  4. If you finish the loop without hitting k spaces, the entire string has k or 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

input: "Hello how are you Contestant", k = 4
HellohowareyouContestant

Splitting on spaces gives us an array of 5 words.

Step 2: Take the first k words

input: "Hello how are you Contestant", k = 4
HellohowareyouContestant

With k = 4, we slice the first four words from the array.

Step 3: Join with spaces

input: "Hello how are you Contestant", k = 4
HellohowareyouContestant
result: "Hello how are you"

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

ApproachTimeSpace
Split-slice-joinO(n), where n is the length of the stringO(n), for the word list
Space countingO(n), where n is the length of the stringO(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