Problem

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.

zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).

Examples

Example 1:

1
2
3
4
5
Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]Explanation: The array ans is built as follows: 
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
    = [0,1,2,4,5,3]

Example 2:

1
2
3
4
5
6
Input: nums = [5,0,1,2,3,4]
Output: [4,5,0,1,2,3]
Explanation: The array ans is built as follows:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
    = [4,5,0,1,2,3]

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] < nums.length
  • The elements in nums are distinct.

Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?

Solution

Method 1 - Iterative

The given problem revolves around constructing a new array ans such that the value at each index i in ans is determined by nums[nums[i]]. Since the input nums is guaranteed to be a zero-based permutation, its elements are distinct integers ranging from 0 to nums.length - 1.

Approach

  • Iterate Through nums: For each index i, compute nums[nums[i]] and store it in the corresponding index of a new array ans.
  • Output Result: Finally, return the filled ans.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public int[] buildArray(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = nums[nums[i]];
        }
        return ans;
    }
}
1
2
3
4
5
6
7
class Solution:
    def buildArray(self, nums: list[int]) -> list[int]:
        n: int = len(nums)
        ans: list[int] = [0] * n
        for i in range(n):
            ans[i] = nums[nums[i]]
        return ans

Complexity

  • ⏰ Time complexity: O(n). The approach involves a single linear iteration through the array nums. Hence, the time complexity is O(n).
  • 🧺 Space complexity: O(n). We use a separate array ans of the same size as nums. Thus, the space complexity is also O(n).