Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Reverse words in string

Sharing is caring!

Problem statement
Given an input string, reverse the string word by word. For example, given s = "the sky is blue", return "blue is sky the".

Solution algorithm
Write a function reverse(string, start, end) that reverses string[start:end]. Reverse entire input string. Iterate over (reversed)words in reversed string and correct them by calling reverse(string, start, end).

  1. Reverse entire string.
  2. Initialise start = 0
  3. Iterate over the string characters.
    • If we hit a ‘ ‘ at index i we note that index i-1 must be the end of a word. Set end = i-1.
    • Reverse substring at [start:end].
    • Update start = i + 1