array manipulation
algorithm
in-place transformation
programming
data structure

Rearrange an array so that arri becomes arrarri with O1 extra space

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In computer science, array manipulation is a fundamental concept with myriad applications in data processing, optimization, and problem-solving. A particularly interesting array transformation challenge is rearranging an array such that each element at index i is replaced by the element at the index currently pointed by arr[i], using only O(1)O(1) extra space. This problem is often encountered in coding interviews and competitive programming.

Problem Statement

Given an array arr[] where each element is within the range of 00 to $n-1$``, rearrange the array so that each element arr[i]becomesarr[arr[i]] using ``$O(1)$ extra space.

Explanation & Approach

The main challenge in solving this problem within the O(1)O(1) extra space constraint is altering the array without losing the original values since they are required to position the reordered values correctly. The key is to refine the approach by encoding additional information into the array elements themselves.

Let’s step through this problem using an example:

Example: Suppose we have an array arr[] = {4, 0, 2, 1, 3}.

  1. Objective: Transform the array so that each element at i becomes arr[arr[i]].
  2. Encode two numbers at each index: You will store the new array values alongside the original ones by encoding them in a single integer. Assume all numbers fit in the array are between 00 and n1n-1.

The formula to encode two numbers x and y is: arr[i]=x+(original_value)×n\text{arr}[i] = x + \text{(original\_value)} \times n In this context, x is the old value, and (original_value) is the new value to be stored.

  1. Decoding the updated value: You can extract the new value and the original value by:
    • New value (arr[arr[i]]): arr[i]÷n\text{arr}[i] \div n
    • Original value: arr[i]modn\text{arr}[i] \mod n

Steps to Implement

  1. Encode the new and old values together:
python
   def rearrange(arr, n):
       for i in range(n):
           arr[i] = arr[i] + (arr[arr[i]] % n) * n
  1. Decode the new values while replacing the array:
python
   def decode_and_replace(arr, n):
       for i in range(n):
           arr[i] = arr[i] // n
  1. Driver function: Combine encoding and decoding.
python
1   def rearrange_arr(arr):
2       n = len(arr)
3       rearrange(arr, n)
4       decode_and_replace(arr, n)

Final Output: For arr[] = {4, 0, 2, 1, 3}, post transformation, the result is arr[] = {3, 4, 2, 0, 1}.

Key Considerations

  1. Time Complexity: The algorithm operates in O(n)O(n) time, where nn is the number of elements in the array due to its single pass encoding and decoding steps.
  2. Space Complexity: Since the transformation uses only a constant amount of extra space beyond the input array, the space complexity is O(1)O(1).
  3. Constraints: The approach is limited by integer size since arr[i] + (arr[arr[i]] \% n) * n must fit in the variable type used (typically int).

Use-Cases

  • Permutation problems: The technique is useful in scenarios where permutations of the array need to be transformed without auxiliary storage.
  • Optimal Memory Applications: Situations requiring in-place transformations, like embedded systems or low-memory environments, benefit greatly from this approach.

Summary Table

ConceptDescription
ObjectiveRearrange array such that arr[i] becomes arr[arr[i]].
Time ComplexityO(n)O(n)
Space ComplexityO(1)O(1)
Encoding Formulaarr[i]=arr[i]+(arr[arr[i]] % n)×n\text{arr}[i] = \text{arr}[i] + (\text{arr[arr[i]] \% n}) \times n
Decoding FormulaExtract recycled values from: arr[i]÷n\text{arr}[i] \div n (new value), arr[i]modn\text{arr}[i] \mod n (original value)
Example Inputarr[] = {4, 0, 2, 1, 3}
Example Outputarr[] = {3, 4, 2, 0, 1}

By understanding these principles and employing the outlined strategy, one can effectively tackle this complex array rearrangement challenge in interviews and other algorithm-intensive tasks.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.