<AI/>
enru
Все статьи

Reverse words in a string

LeetCode 151: Reverse the order of words in a string by trimming spaces, reversing each word and then the whole string.

Сложность
Средняя
Автор
Denis Kolpakov
Опубликовано
Темы
#string#two pointers
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

Write a function that reverses the order of words in a string. Words are separated by spaces; there may be multiple spaces between words, and there may be spaces at the beginning and end of the input string.

In the resulting string, words must be separated by a single space, with no leading or trailing spaces.

Constraints

  • The string length is in the range from 1 to 10000
  • The string contains only English letters, digits and spaces
  • There is at least one word in the string

Examples

Input: "the sky is blue"

Answer: "blue is sky the"

Solution

This problem can be solved with a neat trick: we get the answer if we remove extra spaces, then reverse every word in the string, and finally reverse the whole string. Let's walk through the example a good   example.

  • Remove the extra spaces and get a good example
  • Reverse each word in the string and get a doog elpmaxe
  • Finally, reverse the whole string and get the desired result example good a

To implement this algorithm, we need to solve the following subproblems:

  • Removing extra spaces
  • Finding word boundaries in the string
  • Reversing a word or a string

We move the logic for removing extra spaces into a simple separate function trimSpaces.

To find word boundaries, we go through the string character by character:

  • We keep the indices of the start and end of the current word (initially startIdx = 0 and endIdx = 0).
  • As soon as we reach a space, we treat it as the boundary of the word and reverse the part of the string from startIdx to endIdx. Then we move startIdx and endIdx to the next character.

Reversing is also implemented as a simple separate function reverseWord. It's used both to reverse individual words and to reverse the whole string.

typescript
const reverseWord = (s: string, i: number, j: number): string => {
  const strArr = [...s];
 
  while (i < j) {
    const temp = strArr[i];
    strArr[i] = strArr[j];
    strArr[j] = temp;
    i++;
    j--;
  }
 
  return strArr.join('');
};
 
const trimSpaces = (s: string): string => {
  let isStart = true;
  let j = 0;
  let strArr = [...s];
 
  for (let i = 0; i < strArr.length; i++) {
    if (strArr[i] == ' ' && isStart) {
      continue;
    }
 
    strArr[j] = strArr[i];
    isStart = strArr[i] == ' ';
    j++;
  }
 
  if (strArr[j - 1] == ' ') {
    j--;
  }
 
  return strArr.join('').substring(0, j);
};
 
export const reverseWords = (s: string): string => {
  let startIdx = 0;
  let endIdx = 0;
 
  let trimmed = trimSpaces(s);
 
  while (startIdx < trimmed.length) {
    while (endIdx < trimmed.length && trimmed[endIdx] !== ' ') {
      endIdx++;
    }
 
    trimmed = reverseWord(trimmed, startIdx, endIdx - 1);
    startIdx = endIdx + 1;
    endIdx++;
  }
 
  return reverseWord(trimmed, 0, trimmed.length - 1);
};

Complexity Analysis

Time Complexity

We need to go through the string character by character several times:

  • Removing extra spaces
  • Reversing each word in the string
  • Reversing the whole string

The overall complexity is O(n).

Space Complexity

To solve the problem we convert the string into an array of characters. Depending on the programming language, this may or may not require additional memory allocation.

In general, the space complexity is O(n).