Reverse every word in a string

Strings (Advanced Algo) Medium Problems Hard
  • Fun Fact: This problem uses a fundamental concept called 'string manipulation', which is essential in developing search engines and web crawling tools
  • For instance, Google utilizes advanced string manipulation to analyze and index webpages effectively
  • Similarly, Twitter uses string manipulations for tweet processing and data analytics to figure out trending topics
  • This simple problem of reversing words in a string can thus be a stepping stone to understanding more complex string operations used in real-world applications

Given an input string, containing upper-case and lower-case letters, digits, and spaces( ' ' ). A word is defined as a sequence of non-space characters. The words in s are separated by at least one space.


Return a string with the words in reverse order, concatenated by a single space.

Examples:

Input: s = "welcome to the jungle"


Output: "jungle the to welcome"


Explanation: The words in the input string are "welcome", "to", "the", and "jungle". Reversing the order of these words gives "jungle", "the", "to", and "welcome". The output string should have exactly one space between each word.

Input: s = " amazing coding skills "


Output: "skills coding amazing"


Explanation: The input string has leading and trailing spaces, as well as multiple spaces between the words "amazing", "coding", and "skills". After trimming the leading and trailing spaces and reducing the multiple spaces between words to a single space, the words are "amazing", "coding", and "skills". Reversing the order of these words gives "skills", "coding", and "amazing". The output string should not have any leading or trailing spaces and should have exactly one space between each word.

Input: s = "openAI is innovative"

Constraints

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Hints

  • "Splitting the string into words using split(), which automatically removes extra spaces. Reversing the list of words. Joining them back with a single space."
  • "Iterating through the string in reverse, extracting words character-by-character, and storing them in a list. Reconstructing the sentence with spaces in between."

Company Tags

McKinsey & Company Epic Systems IBM Bain & Company Uber Ernst & Young Walmart PayPal Ubisoft HashiCorp Micron Technology Teladoc Health Morgan Stanley Wayfair ARM Swiggy Freshworks Boston Consulting Group Activision Blizzard Nutanix Zomato Broadcom Chewy Reddit Target Google Microsoft Amazon Meta Apple Netflix Adobe