In-place string reversal with two-pointer pass

After recently using the reversal trick to rotate arrays in O(1) space, I realized the exact same logic applies beautifully to strings. Today I tackled LeetCode 151: Reverse Words in a String in C++. Instead of taking the easy route by allocating extra memory to split the string into a new array of words, I solved it entirely in-place. The strategy: 1️⃣ Reverse the entire string. 2️⃣ Reverse each individual word back to its correct orientation. 3️⃣ Use a two-pointer pass to clean up any leading, trailing, or multiple spaces. Connecting the dots between different data structures and seeing how array pointer techniques translate perfectly to strings is incredibly rewarding. #LeetCode #Cpp #DataStructures #Algorithms #TwoPointers 

  • text

To view or add a comment, sign in

Explore content categories