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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code