Reversing a string by copy and in place
Question
Write a function that returns a reversed copy of a string, and a second one that reverses the string where it is, without allocating memory.
Short answer
Copy: build from reverse iterators, time and space. In place: swap characters from both ends moving inward until the indices meet, time, extra space. Take the in-place version by non-const reference, handle empty and odd-length strings, and note that byte-level reversal breaks multi-byte encodings such as UTF-8.
Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.25, p.228; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solutionLessons behind this question
- Algorithms, Growth Rates, and Asymptotic Notation
- Quicksort and Randomized Quicksort
- Sample Spaces, Events, and the Probability Axioms
Start with a free lesson: Probability Fundamentals is part of a free topic. Create a free account, no card needed, to read it in full with worked solutions.
Read it free