Tutorialspoint
Problem
Solution
Submissions

Largest Word in a String

Certification: Basic Level Accuracy: 54.55% Submissions: 11 Points: 10

Write a C++ program that finds the largest word in a given string. If there are multiple words with the same maximum length, return the first one.

Example 1
  • Input: string = "I love programming"
  • Output: "programming"
  • Explanation:
    • Step 1: Split the input string into words ["I", "love", "programming"].
    • Step 2: Find the word with the maximum length.
    • Step 3: Return the longest word "programming" (11 characters).
Example 2
  • Input: string = "C++ is fun"
  • Output: "C++"
  • Explanation:
    • Step 1: Split the input string into words ["C++", "is", "fun"].
    • Step 2: Find the word with the maximum length.
    • Step 3: Return the first longest word "C++" (3 characters), since both "C++" and "fun" have the same length.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • String contains printable ASCII characters
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(n)
ArraysFunctions / MethodsTCS (Tata Consultancy Services)Capgemini
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Split the string into words based on spaces.
  • Track the length of each word and keep the longest one.
  • Handle edge cases where the string is empty or contains only spaces.

Steps to solve by this approach:

 Step 1: Define a function findLargestWord that takes a constant string reference.
 Step 2: Initialize two strings: one to track the largest word and one for the current word.
 Step 3: Iterate through each character in the input string.
 Step 4: If the character isn't a space, add it to the current word.
 Step 5: If it is a space, compare the current word length with the largest word length.
 Step 6: Update the largest word if necessary and reset the current word.
 Step 7: Check the last word after the loop and return the largest word.

Submitted Code :