Truncate Sentence (LeetCode 1816): Solution and Explanation
Keep only the first k words of a sentence. Because words are separated by single spaces, the k-th space marks the end of the k-th word, so one scan that counts spaces finds the cut.
Intuition
With exactly one space between words and none at the ends, every space closes one word. The first space ends word 1, the second ends word 2, and so on.
So there is no need to split the sentence into a list. Walk the characters, count spaces down from k, and when the count hits 0 the answer is everything before that space.
If the scan reaches the end first, the sentence has exactly k words and is returned as it is.
Approach: Count spaces
- Scan s from left to right.
- At each space, decrease k by 1.
- When k becomes 0 at index i, return s[0..i-1].
- If the loop finishes, return s unchanged.
Step-by-step example
s = "Hello how are you Contestant", k = 4
- Read "Hello", then the space at index 5: k = 3.
- Read "how", then the space at index 9: k = 2.
- Read "are", then the space at index 13: k = 1.
- Read "you", then the space at index 17: k = 0.
- Cut before index 17 and return "Hello how are you".
Code: Python, Java, C++
1class Solution:
2 def truncateSentence(self, s: str, k: int) -> str:
3 for i, ch in enumerate(s):
4 if ch == ' ':
5 k -= 1
6 if k == 0:
7 return s[:i]
8 return s1class Solution {
2 public String truncateSentence(String s, int k) {
3 for (int i = 0; i < s.length(); i++) {
4 if (s.charAt(i) == ' ') {
5 k--;
6 if (k == 0) {
7 return s.substring(0, i);
8 }
9 }
10 }
11 return s;
12 }
13}1class Solution {
2public:
3 string truncateSentence(string s, int k) {
4 for (int i = 0; i < s.size(); i++) {
5 if (s[i] == ' ') {
6 k--;
7 if (k == 0) {
8 return s.substr(0, i);
9 }
10 }
11 }
12 return s;
13 }
14};Time and space complexity
O(n)
At most one pass over the n characters.
O(1)
Only a counter, apart from the returned substring.
Other approaches
Split and join (time O(n), space O(n))
Split on spaces, take the first k words and join them with single spaces. Short to write, but it builds a list of every word.
Build the answer word by word (time O(n), space O(n))
Append characters to a builder until the k-th space appears. Same idea as counting, with an explicit copy as you go.
Common mistakes
- Including the k-th space in the answer. The cut happens just before it.
- Expecting a k-th space when k equals the number of words. There is none, so the whole sentence must be returned after the loop.
- Reading the problem as asking for k characters instead of k words.
Frequently asked questions
Why does counting spaces work?
Words are separated by exactly one space and there are no leading or trailing spaces, so the k-th space is right after the k-th word.
Is splitting the string acceptable in an interview?
Yes, it is correct and O(n). The scan shows you can avoid the extra list, which is a good follow-up to mention.
Can k be larger than the number of words?
No. The constraints guarantee k is at most the number of words, so the answer is always the first k words.