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 Split and Join Approach INPUT Sentence s: "My dog ate his homework" Words in sentence: My [0] dog [1] ate [2] his [3] homework [4] Parameter k: k = 3 Keep only first 3 words Total words: 5 ALGORITHM STEPS 1 Split by Space s.split(" ") creates array ["My","dog","ate","his","homework"] 2 Take First k Words slice(0, k) or loop k times My dog ate his homework 3 Join with Space join(" ") combines words "My" + " " + "dog" + " " + "ate" 4 Return Result Truncated sentence ready Time: O(n) | Space: O(n) FINAL RESULT Truncated Sentence: My dog ate "My dog ate" OK - Success! Verification: Words kept: 3 (k=3) Words removed: 2 Output matches expected Key Insight: The Split and Join approach leverages built-in string methods for efficient word manipulation. split(" ") converts the sentence into an array of words, slice(0,k) takes first k elements, and join(" ") reconstructs the truncated sentence. Simple, readable, and O(n) time complexity. TutorialsPoint - Truncate Sentence | Split and Join Approach
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