Tutorialspoint
Problem
Solution
Submissions

Reverse Words in a Sentence

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a C# program to implement the ReverseWords(string sentence) function, which reverses the order of words in a given sentence while preserving the order of characters within each word. Spaces separate words. The function should return the sentence with reversed word order.

Example 1
  • Input: sentence = "Hello World"
  • Output: "World Hello"
  • Explanation: The sentence has two words: "Hello" and "World"
    • After reversing the order, we get: "World Hello"
Example 2
  • Input: sentence = "The quick brown fox"
  • Output: "fox brown quick The"
  • Explanation: The sentence has four words: "The", "quick", "brown", and "fox"
    • After reversing the order, we get: "fox brown quick The"
Constraints
  • 0 ≤ sentence.length ≤ 10^4
  • The sentence contains English letters (lower-case and upper-case), digits, spaces, and basic punctuation
  • There are no leading or trailing spaces
  • Words are separated by a single space
  • Time Complexity: O(n)
  • Space Complexity: O(n)
ArraysStringsPwCDropbox
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 sentence into an array of words
  • Reverse the array of words
  • Join the reversed array back into a sentence
  • Consider edge cases like empty strings or sentences with only one word


Submitted Code :