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).
"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 <= 500k is in the range [1, the number of words in s].s consist of only lowercase and uppercase English letters and spaces.s are separated by a single space.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.
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.
Time Complexity: O(n), Space Complexity: O(1)
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.
Time Complexity: O(n), Space Complexity: O(1)
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).
Python
Java
C++
Go
TypeScript
JavaScript
Python
| Approach | Complexity |
|---|---|
| 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 | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Split and Join Method | O(n) | O(n) | Best for readability and fast implementation using built-in string utilities |
| In-place Character Scan | O(n) | O(1) | Useful when minimizing memory allocations or demonstrating manual string traversal |
1816. Truncate Sentence | Leetcode Weekly Contest 236 • Ayushi Rawat • 1,844 views views
Watch 9 more video solutions →Practice Truncate Sentence with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor