Truncate Sentence Solution in Python

Code Solution


class Solution:
    def truncateSentence(self, s: str, k: int) -> str:
        return ' '.join(s.split()[:k])

Problem Description

Ah, the classic “Truncate Sentence” problem! It’s like trying to explain your weekend plans to a friend who just can’t handle more than three words. You know, the kind of friend who would rather hear “Netflix, snacks, sleep” than your elaborate tale of a wild adventure.

In this LeetCode challenge, you are given a sentence (a string) and a number k. Your mission, should you choose to accept it, is to truncate the sentence to only the first k words. It’s like being at a party and realizing you’ve been talking too long—time to cut it short!

Approach

The provided solution takes advantage of Python’s string manipulation capabilities. Here’s a brief breakdown of the approach:

  1. Split the Sentence: The split() method breaks the sentence into a list of words.
  2. Slice the List: We take the first k words using list slicing.
  3. Join the Words: Finally, we join these words back into a single string with spaces in between.

Time and Space Complexity

Time Complexity: O(n), where n is the number of characters in the string. This is because we need to split the string and then join it back together.

Space Complexity: O(n) as well, since we are storing the split words in a list.

Real-World Example

Imagine you’re at a coffee shop, and you order a “venti caramel macchiato with extra foam, a blueberry muffin, and a side of avocado toast.” But your friend only wants to hear about the coffee. So, you truncate your order to just “venti caramel macchiato.” That’s exactly what this problem is about—keeping it short and sweet!

Similar Problems

If you enjoyed this problem, you might also like these: