We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Truncate Sentence

Number: 1944

Difficulty: Easy

Paid? No

Companies: Amazon, Bloomberg


Problem Description

Given a sentence s, which is a string consisting of words separated by a single space, and an integer k, the task is to truncate the sentence such that it only contains the first k words.


Key Insights

  • The sentence is safely split into words using the space character.
  • Extracting the first k words can be efficiently achieved by list slicing.
  • The final result is obtained by joining the selected words with a space.
  • The operation is straightforward with a linear pass through the string.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string (due to the split operation).
Space Complexity: O(n), for storing the list of words.


Solution

The problem can be solved by:

  1. Splitting the input string into an array of individual words.
  2. Slicing the resulting array to extract the first k words.
  3. Joining these k words back into a single string with spaces between them. This approach works efficiently given the constraints and makes use of basic string and array operations.

Code Solutions

# Define the function to truncate the sentence
def truncateSentence(s: str, k: int) -> str:
    # Split the sentence into a list of words using space as a delimiter
    words = s.split(" ")
    # Extract the first k words
    truncated_words = words[:k]
    # Join those words back together into a single string with spaces
    return " ".join(truncated_words)

# Example usage
s = "Hello how are you Contestant"
k = 4
print(truncateSentence(s, k))  # Expected output: "Hello how are you"
← Back to All Questions