Problem Description
Given a zero-based permutation array nums, construct an answer array ans of the same length where each element ans[i] is assigned the value nums[nums[i]]. In other words, for every index i, set ans[i] = nums[nums[i]]. The array nums is a permutation of integers ranging from 0 to nums.length - 1.
Key Insights
- The problem is a simple simulation: use the given nums array to build a new array where each element is determined by another indexed lookup in nums.
- A direct approach uses extra memory O(n): simply iterate through the array and build a new array with ans[i] = nums[nums[i]].
- For the follow-up with O(1) extra space, modify the original array in-place by encoding both the new and the old value in each element. This can be done using modulo arithmetic, leveraging the fact that nums is a permutation.
- Ensure careful handling of the encoding/decoding steps to extract the updated val without losing the original information.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(n) for the extra memory approach, and O(1) for the in-place modification approach (excluding the space for input/output).
Solution
The approach involves two main strategies. The first is straightforward: create a new array and for each index i, set ans[i] = nums[nums[i]]. This uses extra O(n) space.
For the in-place solution (O(1) space), use the modulo encoding trick:
- Iterate over each index and update nums[i] by adding (nums[nums[i]] % n) multiplied by n. Here, n is the length of the array. This step encodes both the old and new values into the current element.
- After all elements have been updated, iterate again to decode the new values by dividing each element by n.
Key data structures include arrays, and the main algorithmic approach is simulation combined with in-place encoding to optimize space usage.