Truncate Sentence - Problem

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 & Output

Example 1 — Basic Case
$ Input: s = "My dog ate his homework", k = 3
Output: "My dog ate"
💡 Note: Take the first 3 words: "My", "dog", "ate". Join them with spaces to get "My dog ate".
Example 2 — Single Word
$ Input: s = "chomp chomp chomp", k = 1
Output: "chomp"
💡 Note: Take only the first word "chomp" since k=1.
Example 3 — All Words
$ Input: s = "Hello world", k = 3
Output: "Hello world"
💡 Note: k=3 but sentence only has 2 words, so return entire sentence "Hello world".

Constraints

  • 1 ≤ s.length ≤ 500
  • k is a positive integer
  • 1 ≤ k ≤ number of words in s
  • s consists of only lowercase and uppercase English letters and spaces

Visualization

Tap to expand
Truncate Sentence: Keep First k WordsInput:s = "My dog ate his homework", k = 3Words:Mydogatehishomework✓ Keep✓ Keep✓ Keep✗ Remove✗ RemoveTake first k=3 words and join with spacesOutput:"My dog ate"Result: First 3 words joined by spaces
Understanding the Visualization
1
Input
Sentence string and target word count k
2
Process
Identify and select first k words
3
Output
Truncated sentence with exactly k words
Key Takeaway
🎯 Key Insight: Process only as many characters as needed to find k complete words
Asked in
Amazon 25 Microsoft 18
25.0K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen