Given a string s containing words separated by single spaces and an integer k, truncate the sentence so that it contains only the first k words. Return the resulting string with words still separated by single spaces, without any trailing spaces.
For example, truncating "Hello how are you Contestant" to k=4 produces "Hello how are you". Truncating "What is the solution" to k=3 produces "What is the". If k = 0 or the string is empty, return an empty string. If k is greater than or equal to the number of words, return the full string unchanged.
Truncating a sentence is a common text processing operation used in preview generation, summary creation, content clipping, and teaser text. Social media feeds, search engine results, and article listings all use sentence truncation to show snippets while hiding longer content behind a "read more" link.
The simplest approach splits the string by spaces into an array of words, takes the first k elements using slice, and joins them back with a single space separator. This approach is concise and handles all edge cases correctly: if k exceeds the word count, slice returns all words; if k is 0, slice returns an empty array, and join produces an empty string.
Edge cases include an empty input string (return ""), k=0 (return "" regardless of input), k larger than the word count (return the original string), and a single-word string (return that word if k >= 1, or empty string if k = 0). The solution must preserve the original spacing between words for the truncated portion.
Example Input & Output
Single word
First 4 words
First 2 words
First 3 words
Zero words
Algorithm Flow
Solution Approach
Split the string by spaces, take the first k words, and join them back with a single space.
Split the string on spaces to get an array of words. Use slice(0, k) to extract the first k words. Join them back with a single space separator. If k is larger than the number of words, slice returns the entire array, and join reproduces the full string. If k is 0 or the string is empty, the result is an empty string.
Time complexity is O(n) where n is the string length. Space complexity is O(n) for the split array and the result string.
Best Answers
class Solution {
public String solution(String s, int k) {
String[] w=s.split(" ",-1);
StringBuilder r=new StringBuilder();
for(int i=0;i<k&&i<w.length;i++){r.append(w[i]);if(i<k-1)r.append(' ');}
return r.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
