What does “in-place” mean?

In programming problems, we often encounter the requirements of implementing something "in-place".

For example:

Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

**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. In Java, character array can be used instead of string to perform string operations in place.

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, as well as the example problem given at the beginning of this article.

推荐阅读更多精彩内容

  • 分析原因 起初无法安装 devDependencies 下依赖包,急的不行,以为是 npm 版本有问题,陆续安...
    dkvirus阅读 6,114评论 6 6
  • 国破山河碎, 人伤意缠绵。 非是兴来笔, 只是感生艰。
    古风长歌阅读 110评论 0 2
  • 一直想聊聊目前股市熊市的根本原因,想要聊的通俗易懂甚是不容易。借着王菲的天价演唱会门票,王思聪道出了游戏规则被捅破...
    牛人看股阅读 109评论 0 0
  • 文字能力很重要,润色前和润色后的文章情感相差很大,谢谢我的专属馒头给我指点。特此记录一下。 首先,我要问在座的各位...
    扑腾的猫阅读 254评论 0 1