#1816

Truncate Sentence

Easy
ArrayStringArrayString
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach efficiently splits the sentence into words and directly constructs the truncated sentence using slicing, which is faster and avoids unnecessary string concatenation.

⚙️

Algorithm

3 steps
  1. 1Step 1: Split the sentence into words using space as the delimiter.
  2. 2Step 2: Use slicing to get the first k words.
  3. 3Step 3: Join the sliced words back into a single string and return it.
solution.py4 lines
1s = 'Hello how are you Contestant'
2k = 4
3truncated = ' '.join(s.split()[:k])
4print(truncated)

Complexity note: The time complexity is O(n) because we only traverse the string once to split it into words, and the space complexity is O(n) due to storing the words in an array.

  • 1Understanding how to split strings is crucial.
  • 2Slicing arrays can significantly optimize performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.