Truncate Sentence

Easy
228.

Truncate Sentence

Truncate Sentence is an easy coding problem on arrays and strings, asked in Amazon and Cognizant interviews.

A sentence is a list of words separated by single spaces, with no leading or trailing spaces.

Given a sentence s and an integer k, truncate s so that it contains only the first k words, and return the result.

Example 1

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

Example 2

Input
s = "What is the solution to this problem", k = 4
Output
What is the solution

Example 3

Input
s = "chopper is not a tanuki", k = 5
Output
chopper is not a tanuki
Explanation
k equals the word count, so nothing is dropped.

Constraints

  • 1 <= s.length <= 60
  • 1 <= k <= number of words in s
  • s contains only English letters and single spaces.
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
var truncateSentence = function(s, k) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Truncate Sentence — Solution in Python, Java & C++

Truncate Sentence solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and strings.

Truncate Sentence is an easy coding problem on arrays and strings, asked in Amazon and Cognizant interviews.

  • Difficulty: Easy
  • Topics: Arrays, Strings
  • Asked at: Amazon, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

A sentence is a list of words separated by single spaces, with no leading or trailing spaces.

Given a sentence s and an integer k, truncate s so that it contains only the first k words, and return the result.

Example 1

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

Example 2

Input: s = "What is the solution to this problem", k = 4
Output: What is the solution

Example 3

Input: s = "chopper is not a tanuki", k = 5
Output: chopper is not a tanuki
Explanation: k equals the word count, so nothing is dropped.

Constraints

  • 1 <= s.length <= 60
  • 1 <= k <= number of words in s
  • s contains only English letters and single spaces.

Hints for Truncate Sentence

  1. Hint 1

    Split on the space, take the first k pieces, and join them back with a space.

  2. Hint 2

    Without splitting: count spaces as you scan and stop at the k-th one.

How to solve Truncate Sentence

Split on spaces, keep the first k words, and rejoin.

Approach

  1. Split s on " ".
  2. Take the first k pieces and join with a space.

Why it works

Words are separated by exactly one space with none at the ends, so the split-slice-join round-trips the format.

Complexity

  • Time — O(n)
  • Space — O(n)

Pitfalls

  • Without splitting, scan and stop at the k-th space — return the prefix before it.

Reference solution

Python

def truncateSentence(s: str, k: int) -> str:
    return " ".join(s.split(" ")[:k])

Java

public static String truncateSentence(String s, int k) {
    String[] pieces = s.split(" ");
    StringBuilder out = new StringBuilder();
    for (int i = 0; i < k && i < pieces.length; i++) {
        if (i > 0) out.append(' ');
        out.append(pieces[i]);
    }
    return out.toString();
}

C++

string truncateSentence(string s, int k) {
    int spaces = 0;
    for (int i = 0; i < (int) s.size(); i++) {
        if (s[i] == ' ') {
            spaces++;
            if (spaces == k) return s.substr(0, i);
        }
    }
    return s;
}

JavaScript

var truncateSentence = function(s, k) {
    return s.split(" ").slice(0, k).join(" ");
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 1199 arrays problems · the whole catalogue

Learn the technique: Arrays · Strings