algoadvance

You are given a sentence s and an integer k. You need to truncate the sentence such that it contains only the first k words. Return the truncated sentence.

Example 1:

Input: s = "Hello how are you Contestant", k = 4
Output: "Hello how are you"

Example 2:

Input: s = "What is the solution to this problem", k = 4
Output: "What is the solution"

Example 3:

Input: s = "chopper is not a tanuki", k = 5
Output: "chopper is not a tanuki"

Clarifying Questions

  1. Splitting Criteria: Are we assuming words are separated by single spaces and there are no leading/trailing spaces?
    • Yes, we’ll assume that words are separated by single spaces and there’s no leading/trailing whitespace.
  2. Input Constraints: Can the value of k be equal to or greater than the number of words in the sentence?
    • No, k will always be a positive integer less than or equal to the number of words in the sentence.
  3. Character Set: Are we assuming the input sentence only consists of alphabetic characters and spaces?
    • Yes, we can assume the sentence consists only of alphabetic characters and spaces.

Strategy

  1. Split the Sentence: Use Python’s split method to split the sentence s into a list of words based on spaces.
  2. Extract First k Words: Slice the list to get the first k words.
  3. Join the Words: Use the join method to join the words back into a sentence with a single space as the delimiter.
  4. Return the Result: Return the truncated sentence.

Time Complexity

Overall, the time complexity is O(n + k * m), which is typically linear in nature given the constraints.

Code

def truncateSentence(s: str, k: int) -> str:
    # Split the sentence into words
    words = s.split()
    
    # Take the first k words
    truncated_words = words[:k]
    
    # Join the words back into a sentence
    truncated_sentence = ' '.join(truncated_words)
    
    return truncated_sentence

# Test cases
print(truncateSentence("Hello how are you Contestant", 4))  # Expected: "Hello how are you"
print(truncateSentence("What is the solution to this problem", 4))  # Expected: "What is the solution"
print(truncateSentence("chopper is not a tanuki", 5))  # Expected: "chopper is not a tanuki"

This code effectively splits the sentence, takes the first k words, and then rejoins them into the truncated sentence.

Try our interview co-pilot at AlgoAdvance.com