Skip to content

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, O(n)O(n) time and O(n)O(n) space. In place: swap characters from both ends moving inward until the indices meet, O(n)O(n) time, O(1)O(1) 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 solution

Lessons behind this question

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