Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions String/1816. Truncate Sentence.py

This file was deleted.

Empty file.
20 changes: 20 additions & 0 deletions problems/easy/truncate_sentence_1816/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Tags: String


class Solution:
def truncate_sentence(self, s: str, k: int) -> str:
"""
Time complexity: O(n)
Breakdown:
- s.split(): Splits the string into a list of words - O(n) where n is the length of the string
- [:k]: Slices the first k elements from the list - O(k) where k is the number of words to keep
- ' '.join(): Joins k words back into a string - O(n) to construct the result string
Since k <= n (the number of words cannot exceed the string length), overall time complexity is O(n)

Space complexity: O(n)
Breakdown:
- The split() operation creates a list of all words in the string - O(n) space
- The join() operation creates a new string for the result - O(n) space
Overall: O(n) additional space
"""
return ' '.join(s.split()[:k])
15 changes: 15 additions & 0 deletions problems/easy/truncate_sentence_1816/test_solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import pytest
from tests.base_test import BaseTestSolution
from .solution import Solution


class TestSolution(BaseTestSolution):
solution = Solution()

@pytest.mark.parametrize("method_name, s, k, expected, timeout", [
('truncate_sentence', "Hello how are you Contestant", 4, "Hello how are you", None),
('truncate_sentence', "What is the solution to this problem", 4, "What is the solution", None),
('truncate_sentence', "chopper is not a tanuki", 5, "chopper is not a tanuki", None),
])
def test_truncate_sentence(self, method_name, s, k, expected, timeout):
self._run_test(self.solution, method_name, (s, k,), expected, timeout)