Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).
"Hello World", "HELLO", and "hello world hello world" are all sentences.You are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it.
Example 1:
Input: s = "Hello how are you Contestant", k = 4 Output: "Hello how are you" Explanation: The words in s are ["Hello", "how" "are", "you", "Contestant"]. The first 4 words are ["Hello", "how", "are", "you"]. Hence, you should return "Hello how are you".
Example 2:
Input: s = "What is the solution to this problem", k = 4 Output: "What is the solution" Explanation: The words in s are ["What", "is" "the", "solution", "to", "this", "problem"]. The first 4 words are ["What", "is", "the", "solution"]. Hence, you should return "What is the solution".
Example 3:
Input: s = "chopper is not a tanuki", k = 5 Output: "chopper is not a tanuki"
Constraints:
1 <= s.length <= 500k is in the range [1, the number of words in s].s consist of only lowercase and uppercase English letters and spaces.s are separated by a single space.Problem summary: A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation). For example, "Hello World", "HELLO", and "hello world hello world" are all sentences. You are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
"Hello how are you Contestant" 4
"What is the solution to this problem" 4
"chopper is not a tanuki" 5
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1816: Truncate Sentence
class Solution {
public String truncateSentence(String s, int k) {
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == ' ' && (--k) == 0) {
return s.substring(0, i);
}
}
return s;
}
}
// Accepted solution for LeetCode #1816: Truncate Sentence
func truncateSentence(s string, k int) string {
for i, c := range s {
if c == ' ' {
k--
}
if k == 0 {
return s[:i]
}
}
return s
}
# Accepted solution for LeetCode #1816: Truncate Sentence
class Solution:
def truncateSentence(self, s: str, k: int) -> str:
return ' '.join(s.split()[:k])
// Accepted solution for LeetCode #1816: Truncate Sentence
struct Solution;
impl Solution {
fn truncate_sentence(s: String, k: i32) -> String {
let words: Vec<&str> = s.split_whitespace().take(k as usize).collect();
words.join(" ")
}
}
#[test]
fn test() {
let s = "Hello how are you Contestant".to_string();
let k = 4;
let res = "Hello how are you".to_string();
assert_eq!(Solution::truncate_sentence(s, k), res);
}
// Accepted solution for LeetCode #1816: Truncate Sentence
function truncateSentence(s: string, k: number): string {
for (let i = 0; i < s.length; ++i) {
if (s[i] === ' ' && --k === 0) {
return s.slice(0, i);
}
}
return s;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.