Pankaj Tanwar
Published on

Truncate Sentence.

––– views

Problem of the day - Truncate Sentence

Tag - Easy

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._

Input: s = "Hello how are you Contestant", k = 4 Output: "Hello how are you"

Problem seems very simple. I just need to count the spaces and keep on adding the current char to result string and stop once either we reach the end or count is matched.

Here is the code for this -

class Solution {
string truncateSentence(string s, int k) {
string ans = "";
for(auto c: s) {
if(c == ' ') k--;
if(k > 0) {
ans += c;
return ans;

Can I modify the code to make it look better? Shall I split the string by space and add till the count allows? But ahh, It will come at the cost of increase time complexity. Let's leave it as of now.

You might like previous editions of my coding diary