Truncate Sentence Solution in Java


Problem Description

So, you’ve got a sentence that’s longer than your patience during a Monday morning meeting. You need to truncate it to a certain number of words, because let’s face it, nobody has time to read a novel when all you wanted was a quick update. The problem is simple: given a string s and an integer k, return the first k words of the sentence.

Imagine you’re at a party, and someone starts telling you their life story. You just want to know how they got that awesome haircut, but they keep rambling on about their cat’s diet. You’d wish you could just truncate their story to the first few words, right? Well, that’s exactly what this problem is about!

Code Solution


class Solution {
  public String truncateSentence(String s, int k) {
    String[] words = s.split(" ");
    String[] truncated = new String[k];

    for (int i = 0; i < k; ++i)
      truncated[i] = words[i];

    return String.join(" ", truncated);
  }
}

Approach

The approach here is straightforward. We split the input string s into an array of words using the space character as a delimiter. Then, we create a new array to hold the first k words. A simple loop fills this new array, and finally, we join the words back into a single string with spaces in between. Voila! You’ve got your truncated sentence.

Time and Space Complexity

Time Complexity: O(n), where n is the number of characters in the string s. This is because we need to split the string and then join it back together.

Space Complexity: O(k), where k is the number of words we want to keep. We are storing only the first k words in a new array.

Real-World Example

Let’s say you’re scrolling through your social media feed, and you come across a post that reads: “Today I went to the park, had ice cream, and met an old friend.” You only want to see the first two words: “Today I.” This is where the truncate sentence solution comes in handy, allowing you to quickly get the gist of the post without diving into the details.

Similar Problems

2-Sum Solution in Java