19. Rearranging an Array with O(1) Extra Space
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
To rearrange an array with O(1) extra space, I have used the following approach:
Given the constraint that the maximum value of n
is 10^5
, along with a long long
array called arr
, we can leverage this constraint to store both the old and new numbers within the same array elements.
Each array element will consist of a 10-digit number, where the first 5 digits represent the new number obtained after rearrangement, and the last 5 digits represent the old number.
Initially, we set both the new and old numbers at the same index during the iteration. To identify the new number, we consider the first 5 digits of the 10-digit number and obtain the desired number by dividing it by 10^5
.
We can store the array numbers as:
By dividing these numbers by 10^5
, we obtain the desired values:
Time Complexity: O(N)
Auxiliary Space Complexity: O(1)
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.