Truncate Sentence Solution in C++

Problem Description

Ah, the classic “Truncate Sentence” problem! It’s like trying to explain a complex theory to your grandma in just a few words. You know, when you have a long-winded sentence that could put a caffeinated squirrel to sleep, and you just want to cut it down to size? Well, that’s what this problem is all about!

The task is simple: given a sentence s and an integer k, you need to truncate the sentence after the k-th word. If you’re wondering how to count words, just remember that they’re separated by spaces. So, if you have a sentence like “I love programming in C++”, and k is 3, your output should be “I love programming”. Easy peasy, right?

Code Solution


class Solution {
 public:
  string truncateSentence(string s, int k) {
    for (int i = 0; i < s.length(); ++i)
      if (s[i] == ' ' && --k == 0)
        return s.substr(0, i);
    return s;
  }
};

Approach

The approach here is straightforward. We loop through the string s character by character. Every time we encounter a space, we decrement k. When k reaches zero, we know we’ve found the k-th word, and we return the substring from the start of the string to the current index. If we finish the loop without hitting k zero, we simply return the entire string.

Time and Space Complexity

Time Complexity

O(n), where n is the length of the string s. We traverse the string once.

Space Complexity

O(1), as we are using a constant amount of space regardless of the input size.

Real-World Example

Imagine you’re at a party, and you’re trying to introduce yourself to a group of people. You start with "Hi, I’m John Doe, a software engineer who loves coding in C++ and Python, and I also enjoy hiking and reading." But before you can finish, someone interrupts you, and you realize you only have time to say "Hi, I’m John Doe." That’s essentially what this problem is doing—truncating your long-winded introduction to just the essentials!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in C++