Truncate Sentence - Problem
Truncate Sentence is a fundamental string manipulation problem that challenges you to extract the first k words from a given sentence.

You are given a sentence s which is a list of words separated by single spaces with no leading or trailing spaces. Each word consists only of uppercase and lowercase English letters (no punctuation). You are also given an integer k.

Your task is to truncate the sentence so that it contains only the first k words and return the truncated sentence.

For example:
"Hello World Example" with k=2 becomes "Hello World"
"HELLO" with k=1 remains "HELLO"
"hello world hello world" with k=3 becomes "hello world hello"

Input & Output

example_1.py — Basic Truncation
$ Input: s = "Hello World Example", k = 2
Output: "Hello World"
💡 Note: The first 2 words are "Hello" and "World", so we return "Hello World".
example_2.py — Single Word
$ Input: s = "HELLO", k = 1
Output: "HELLO"
💡 Note: The sentence has only one word, and we want the first 1 word, so we return the entire sentence.
example_3.py — k equals word count
$ Input: s = "hello world hello world", k = 4
Output: "hello world hello world"
💡 Note: The sentence has exactly 4 words, and k=4, so we return the entire sentence unchanged.

Constraints

  • 1 ≤ s.length ≤ 500
  • k is a positive integer
  • 1 ≤ k ≤ number of words in s
  • s consists of only uppercase and lowercase English letters and spaces
  • The words in s are separated by single spaces
  • s does not have leading or trailing spaces

Visualization

Tap to expand
"Hello World Example Test Case"12345"Hello World"✓ k=2 words foundAlgorithm Steps:1. Scan string left to right2. Count spaces as word separators3. Stop at kth space position4. Return substring(0, position)Time: O(n) | Space: O(1) | Optimal ⚡
Understanding the Visualization
1
Start Scanning
Begin reading the sentence character by character
2
Count Word Boundaries
Each space represents the end of a word
3
Stop at Target
When we find the kth space, we've found k words
4
Extract Result
Return everything from start to that position
Key Takeaway
🎯 Key Insight: By finding the position of the kth space, we can extract exactly k words in a single pass without needing to split the entire string.
Asked in
Microsoft 25 Amazon 18 Google 12 Meta 8
28.0K Views
Medium Frequency
~15 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