Skip to main content

Truncate Sentence - Solution & Explanation

EasyArrayString13 min readAsked at: Bloomberg
Practice this problem

Problem Statement

A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).

  • For example, "Hello World", "HELLO", and "hello world hello world" are all sentences.

You are given a sentence s​​​​​​ and an integer k​​​​​​. You want to truncate s​​​​​​ such that it contains only the first k​​​​​​ words. Return s​​​​​​ after truncating it.

 

Example 1:

Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".

Example 2:

Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"
Explanation:
The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
The first 4 words are ["What", "is", "the", "solution"].
Hence, you should return "What is the solution".

Example 3:

Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"

 

Constraints:

  • 1 <= s.length <= 500
  • k is in the range [1, the number of words in s].
  • s consist of only lowercase and uppercase English letters and spaces.
  • The words in s are separated by a single space.
  • There are no leading or trailing spaces.

Approach Overview

Problem Overview: You receive a sentence s containing words separated by single spaces and an integer k. The task is to return a new string that contains only the first k words from the sentence. Words must remain in the original order and be separated by a single space.

Approach 1: Split and Join Method (O(n) time, O(n) space)

The straightforward solution uses built-in string utilities. Split the sentence into an array of words using the space delimiter. After that, take the first k elements and join them back into a string using spaces. The key operation is split(), which converts the sentence into a list of tokens. Then a slice or subarray operation selects the first k words before combining them with join(). Time complexity is O(n) because the entire string must be scanned during the split operation. Space complexity is also O(n) since the array of words is stored in memory. This approach is clean, readable, and typically the fastest to implement in interviews or production code when memory constraints are not strict. It relies heavily on standard string manipulation functions available in most languages.

Approach 2: In-place Scan / Character Iteration (O(n) time, O(1) extra space)

A more memory-efficient method scans the sentence character by character and counts spaces. Each space indicates the end of a word. Once you encounter the k-th word boundary, return the substring from index 0 up to that position. This avoids building an intermediate array of words. The algorithm simply iterates through the characters, increments a counter when encountering a space, and stops once k words have been processed. Time complexity remains O(n) because the string may need to be scanned entirely in the worst case. Space complexity is O(1) since only a few counters and indices are used. This approach demonstrates stronger control over memory and low-level operations on string data while avoiding unnecessary allocations. The iteration pattern is similar to linear traversal problems over arrays.

Recommended for interviews: Both approaches run in linear time, which is optimal because every character may need to be inspected. The split-and-join method is usually the quickest to implement and easiest to read, making it perfectly acceptable in most interviews. The in-place scanning approach shows deeper understanding of string traversal and space optimization, which can impress interviewers when they ask for improvements after the initial solution.

Approach 1: Split and Join Method

This approach involves splitting the sentence into words using the space as a delimiter and then joining the first k words back into a sentence.

The function iterates through the string, counting spaces to track the number of words. Upon reaching the k-th word, it replaces the subsequent space with a null terminator to truncate the sentence.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), Space Complexity: O(1)

Try this approach in the editor →

Approach 2: In-place Modification

This method involves iterating over the characters of the string and directly modifying it to terminate at the end of the k-th word.

This implementation traverses the string character by character, counting spaces to identify word boundaries. The sentence ends when the k-th word is reached.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), Space Complexity: O(1)

Try this approach in the editor →

Approach 3: Simulation

We traverse the string s from the beginning. For the current character s[i], if it is a space, we decrement k. When k becomes 0, it means that we have extracted k words, so we return the substring s[0..i).

After the traversal, we return s.

The time complexity is O(n), where n is the length of the string s. Ignoring the space complexity of the answer, the space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

JavaScript

Try this approach in the editor →

Approach 4: Default Approach

Code

Python

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Split and Join Method

Time Complexity: O(n), Space Complexity: O(1)

In-place Modification

Time Complexity: O(n), Space Complexity: O(1)

Simulation—
Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Split and Join MethodO(n)O(n)Best for readability and fast implementation using built-in string utilities
In-place Character ScanO(n)O(1)Useful when minimizing memory allocations or demonstrating manual string traversal

Video Solution

1816. Truncate Sentence | Leetcode Weekly Contest 236 • Ayushi Rawat • 1,847 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Truncate Sentence easy or hard?
Truncate Sentence is classified as an Easy problem on LeetCode with a high acceptance rate above 80%. It primarily tests basic string manipulation, iteration, and understanding of word boundaries.
Truncate Sentence Python/Java solution
In Python, use s.split() to create a list of words and return ' '.join(words[:k]). In Java, use s.split(" ") and append the first k words with a StringBuilder or join them directly. Both implementations run in O(n) time.
How to solve Truncate Sentence in O(n)?
Iterate through the string and count spaces to detect word boundaries. Once the k-th word is reached, return the substring from index 0 to that position. This single-pass scan processes each character once, giving O(n) time complexity and O(1) extra space.
What is the best approach for Truncate Sentence?
The most practical approach is the split-and-join method. Split the sentence into words, take the first k elements, and join them back with spaces. It runs in O(n) time and O(n) space and is easy to implement in languages like Python, Java, and JavaScript.
Is Truncate Sentence asked at Google/Amazon/Meta?
Problems involving string parsing and word boundaries appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may appear less often, its pattern of scanning strings and handling delimiters is very common in coding interviews.
What data structure is used in Truncate Sentence?
The problem mainly relies on string processing. The split-based approach temporarily stores words in an array or list, while the in-place scanning approach works directly on the string without additional data structures.
What is the time complexity of Truncate Sentence?
The time complexity is O(n), where n is the length of the input string. Every character must be scanned at least once either during splitting or while iterating through the sentence to count spaces.

Ready to solve this problem?

Practice Truncate Sentence with our built-in code editor and test cases.

Practice on FleetCode