views:

334

answers:

3

Reverse words in a string (words are separated by one or more spaces). Now do it in-place.

What does in-place mean?

+16  A: 

In-place means that you should update the original string rather than creating a new one.

Depending on the language/framework that you're using this could be impossible. (For example, strings are immutable in .NET and Java, so it would be impossible to perform an in-place update of a string without resorting to some evil hacks.)

LukeH
For .NET or Java the question could be rephrased to talk about an array of chars or a StringBuilder
Simon Nickerson
+3  A: 

You should change the content of the original string to the reverse without using a temporary storage variable to hold the string.

Chaoz
Isn't this impossible? You'd at least need a loop counter or pointer, probably 2.
Simon Nickerson
Well, I meant a storage variable to hold temporary values. Depending on the language you'll indeed need a counter or a pointer.
Chaoz
+6  A: 

In-place algorithms can only use O(1) extra space, essentially. Array reversal (essentially what the interview question boils down to) is a classic example. The following is taken from Wikipedia:

Suppose we want to reverse an array of n items. One simple way to do this is:

function reverse(a[0..n])
    allocate b[0..n]
    for i from 0 to n
       b[n - i] = a[i]
    return b

Unfortunately, this requires O(n) extra space to create the array b, and allocation is often a slow operation. If we no longer need a, we can instead overwrite it with its own reversal using this in-place algorithm:

function reverse-in-place(a[0..n])
    for i from 0 to floor(n/2)
       swap(a[i], a[n-i])

Sometimes doing something in-place is VERY HARD. A classic example is general non-square matrix transposition.

See also

polygenelubricants
is non-square matrix transposition even possible to do in-place? Surely it requires different dimensions on each side.a 2x3 array becoming a 3x2 array?
penguat
@penguat: the matrix would be stored in a 1D array of 6 elements. Transposition switches from row-major to column-major and vice versa, e.g. `ABCDEF` to `ADBECF`.
polygenelubricants
Ah. Yes, I see now how an in-place transposition could be tricky, and require an awful lot of thinking before implementation.
penguat