Leetcode 1816: Truncate Sentence

grid47
grid47
Exploring patterns and algorithms
May 9, 2024 4 min read

Given a sentence with words separated by a space, truncate the sentence to contain only the first k words. Return the truncated sentence.
Problem
Approach
Steps
Complexity
Input: The input consists of a sentence s and an integer k.
Example: s = "Sunshine and rainbows are beautiful", k = 3
Constraints:
• 1 <= s.length <= 500
• k is in the range [1, the number of words in s].
• s consists of only lowercase and uppercase English letters and spaces.
• The words in s are separated by a single space.
• There are no leading or trailing spaces in s.
Output: Return the sentence containing only the first k words.
Example: Output: "Sunshine and rainbows"
Constraints:
• The output should be a string representing the truncated sentence.
Goal: Truncate the sentence to contain only the first k words.
Steps:
• Split the sentence into words.
• Select the first k words.
• Join the selected words into a new sentence and return it.
Goal: The input string will always meet the constraints listed below.
Steps:
• The sentence will not have any leading or trailing spaces.
• The words are separated by exactly one space.
Assumptions:
• The sentence contains at least one word.
• The value of k is always valid and within the range of words in the sentence.
Input: s = "Sunshine and rainbows are beautiful", k = 3
Explanation: The first 3 words are "Sunshine", "and", "rainbows".

Input: s = "Learn to code at any time", k = 5
Explanation: The sentence contains exactly 5 words, so the entire sentence is returned.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus