Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Reverse the words in a sentence

    EasyAbout 15 minFreeLearn it: The C# Angle: Collection Costs, LINQ Costs, Strings and Span in Coding Interviews

    The task

    A chat app has a playful "backwards" mode: it shows a message with its words in reverse order, while each word keeps its own letters.

    Complete ReverseWords(string sentence). Return the words in reverse order. Words are separated by one or more ordinary spaces; remove spaces at the start and the end, and put exactly one space between words in the result. If there are no words, return an empty string. The sentence is never null and holds only lowercase English letters and spaces.

    Signature

    public static string ReverseWords(string sentence)

    Examples

    • "deploy the new build" → "build new the deploy". The words move; their letters do not.
    • " ship it " → "it ship". Extra spaces disappear.

    Limits: Up to 100,000 characters.

    The tests check: an empty sentence, only spaces, one word, two words, spaces at the start and the end, several spaces between words, spaces around a single word, repeated words, and a sentence of 20,000 words.

    Hints

      The solution opens by itself when all tests pass. You remember more if you try first.

      Sign in to see the solution

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public static class Solution
      {
          // Returns the words in reverse order, separated by single spaces.
          public static string ReverseWords(string sentence)
          {
              throw new NotImplementedException();
          }
      }

      Sign in to run and submit your code. It stays here while you do.