Home

Truncate Sentence

An architect drawing a house Photo by Alexandra

This post is part of the Algorithms Problem Solving series.

Problem description

This is the Truncate Sentence problem. The description looks like this:

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.

Examples

Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"
Explanation:
The words in s are ["Hello", "how" "are", "you", "Contestant"].
The first 4 words are ["Hello", "how", "are", "you"].
Hence, you should return "Hello how are you".
Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"
Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"
Explanation:
The words in s are ["What", "is" "the", "solution", "to", "this", "problem"].
The first 4 words are ["What", "is", "the", "solution"].
Hence, you should return "What is the solution".

Solution

I have three versions:

Solving using all Python power with split

def truncate_sentence(s, k):
    return ' '.join(s.split(' ')[0:k])

Solving without Python split

def truncate_sentence(s, k):
    start_index, end_index, words = 0, 0, []

    for index, char in enumerate(s):
        end_index = index

        if char == ' ':
            words.append(s[start_index:end_index])
            start_index = index + 1

    words.append(s[start_index:])

    return ' '.join(words[:k])

Resources

Have fun, keep learning, and always keep coding!

My Twitter and Github

Patreon Become a Patron Coffee icon Buy me a coffee