Truncate Sentence — Solution in Python, Java & C++
Truncate Sentence solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem on arrays and strings.
Truncate Sentence is an easy coding problem on arrays and strings, asked in Amazon and Cognizant interviews.
- Difficulty: Easy
- Topics: Arrays, Strings
- Asked at: Amazon, Cognizant
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A sentence is a list of words separated by single spaces, with no leading or trailing spaces.
Given a sentence s and an integer k, truncate s so that it contains only the first k words, and return the result.
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
Explanation: k equals the word count, so nothing is dropped.
Constraints
1 <= s.length <= 601 <= k <= number of words in ss contains only English letters and single spaces.
Hints for Truncate Sentence
Hint 1
Split on the space, take the first
kpieces, and join them back with a space.Hint 2
Without splitting: count spaces as you scan and stop at the k-th one.
How to solve Truncate Sentence
Split on spaces, keep the first k words, and rejoin.
Approach
- Split
son" ". - Take the first
kpieces and join with a space.
Why it works
Words are separated by exactly one space with none at the ends, so the split-slice-join round-trips the format.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- Without splitting, scan and stop at the
k-th space — return the prefix before it.
Reference solution
Python
def truncateSentence(s: str, k: int) -> str:
return " ".join(s.split(" ")[:k])Java
public static String truncateSentence(String s, int k) {
String[] pieces = s.split(" ");
StringBuilder out = new StringBuilder();
for (int i = 0; i < k && i < pieces.length; i++) {
if (i > 0) out.append(' ');
out.append(pieces[i]);
}
return out.toString();
}C++
string truncateSentence(string s, int k) {
int spaces = 0;
for (int i = 0; i < (int) s.size(); i++) {
if (s[i] == ' ') {
spaces++;
if (spaces == k) return s.substr(0, i);
}
}
return s;
}JavaScript
var truncateSentence = function(s, k) {
return s.split(" ").slice(0, k).join(" ");
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.