LeetCode #151: Reverse Words in a String — Flip Everything, Then Each Word
Brute To Best
0:00 / 0:00
LeetCode #151: Reverse Words in a String — Flip Everything, Then Each Word
1 просмотр · 12 дней назад
Brute To Best
57 подписчиков
1 просмотр · 12 дней назад
Problem #151 of the Brute To Best series: Reverse Words in a String.
Reverse the order of the words, collapsing every run of spaces to a single space with none at the ends. Splitting on whitespace and joining the reversed list is one line in most languages; the follow-up asks for in-place on a character array, where the trick is to reverse twice.
In this video:
What the output must look like: single spaces, no leading or trailing The one-liner: split on whitespace, reverse the list, join with a space Why the split must treat multiple spaces as one separator The manual version: scan from the end, collect each word, append it Why that needs care at the boundaries between words The in-place approach on a character array: reverse the entire string first Then reverse each individual word back to normal Why two reversals restore the letters but not the order Cleaning the spaces with a read and write pointer in the same array Why the write pointer gives you the final length Handling a string that is only spaces Dry run with " the sky is blue " reaching "blue is sky the" Time O(n), space O(1) on a character array
LeetCode 151 — Reverse Words in a String: https://leetcode.com/problems/reverse...
The reverse-all-then-reverse-parts trick also rotates an array in place in Rotate Array.
Earlier in the series: problems #1 to #150, in order.
Subscribe to Brute To Best — every problem, from the brute force to the best solution.
#leetcode #reversewordsinastring #strings #twopointers #inplace #stringmanipulation #dsa #coding #codinginterview #problemsolving #datastructuresandalgorithms #leetcodesolutions #brutetobest #mediumproblems