Array / String· 25 min

Reverse Words in a String

LeetCode #151 · Medium · Interactive step-by-step visualization

Setup

Example inputs = " the sky is blue "
Step 1 / 6

Current step

1 / 6

Normalize the sentence. Leading, trailing and repeated spaces do not belong in the output. " the sky is blue " splits into [the, sky, is, blue].

Step log

raw

" the sky is blue "

Active cursor
Comparing
Best or completed
Leaving or removed
reverse-words-in-a-string.java
1public String reverseWords(String s) {
2 String[] words = s.trim().split("\s+");
3 int left = 0, right = words.length - 1;
4 while (left < right) {
5 String temp = words[left];
6 words[left++] = words[right];
7 words[right--] = temp;
8 }
9 return String.join(" ", words);
10}
● Java
Time
O(n)
Space
O(n)
Pattern
two pointers
Frames
6