File: truncate-sentence/solution.py

Date: 2026-06-06

Time: 19:31

truncate-sentence/solution.py

Purpose

This file implements the solution to LeetCode 1816 — Truncate Sentence. It owns exactly one responsibility: given a sentence string and an integer k, return the first k words of that sentence as a single space-separated string.

Key Components

Solution.truncateSentence(self, s: str, k: int) -> str — The sole method. It splits the input on whitespace, slices the first k elements, and joins them back with spaces.

The implementation is a single expression: " ".join(s.split()[:k]). No intermediate state, no mutation.

Patterns

Dependencies

Imports: None — uses only Python builtins (str.split, str.join, list slicing).

Imported by: The "Imported By" list in the prompt is misleading — those are test files from *other* problems that happen to share a common test harness import pattern (likely importing Solution from their own solution.py). The actual consumer is truncate-sentence/test_solution.py.

Flow

1. s.split() tokenizes the sentence on any whitespace, producing a list[str].

2. [:k] slices the first k words. If k >= len(words), it returns all words (no error).

3. " ".join(...) reassembles the words with single spaces.

The entire method is a pure function — no side effects, no state.

Invariants

Error Handling

None. The method trusts its inputs per LeetCode's guarantees. If k exceeds the word count, Python's slice semantics silently return all available words — which is correct behavior, not a bug.

Topics to Explore

Beliefs