Code Logo

Truncate Sentence

Published at25 Jul 2026
Medium 0 views
Like0

A sentence is a list of words separated by spaces. Given a sentence s and an integer k, return the first k words of the sentence. If k is 0, return an empty string.

Split the sentence into words by spaces, take the first k words, and join them back with spaces. Handle the case where k is larger than the number of words (return the whole sentence) and k is 0 (return empty string).

Time complexity is O(n) for splitting and O(k) for joining. Space complexity is O(n) for the word array.

Example Input & Output

Example 1
Input
"single",1
Output
"single"
Explanation

Single word

Example 2
Input
"Hello how are you Contestant",4
Output
"Hello how are you"
Explanation

First 4 words

Example 3
Input
"a b c d e f",2
Output
"a b"
Explanation

First 2 words

Example 4
Input
"What is the solution",3
Output
"What is the"
Explanation

First 3 words

Example 5
Input
"one two three",0
Output
""
Explanation

Zero words

Algorithm Flow

Recommendation Algorithm Flow for Truncate Sentence
Recommendation Algorithm Flow for Truncate Sentence

Solution Approach

function solution(s, k) {
  return s.split(' ').slice(0, k).join(' ');
}

Best Answers

java
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();
    }
}