Truncate Sentence | LeetCode 1816 | Python | Solution

Here is the problem link.

Problem Overview

This is an easy problem, and it’s basically a string-related problem. I hope you already read the problem description from the given link.

So we will be given a string and an integer. The given string is basically a sentence which is a list of words separated by a single space. There are no leading or trailing spaces.

We have to return the first k (k is the given integer) number of words. Let’s see an example. Suppose the given string is: Python programming language and the given integer is 1.

Python programming language
  |        |          |
  1        2          3

As the given integer is 1, the answer will be Python. If the integer is 2, then the answer will Python programming.

Coding Part

The coding part is pretty straightforward. First of all, we will split the string by space. Then we will get each word as a separate element in an array. After that, we can easily get the first k number of words from the array.

Let’s see the solution.

class Solution:
    def truncateSentence(self, s: str, k: int) -> str:

        
        array = s.split(' ')
        array = array[:k]
        result = ' '.join(array)
        
        return result
            
        
        # One Line Solution
        # return ' '.join(s.split(' ')[:k])

Last Words

There are many solutions to this problem. I hope this one will help you.

This answer will be accepted. But before submitting an answer, try to understand the whole thing. And try to go through the code with a simple test case for better understanding. It helps a lot.

Scroll to Top