Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Every permutation value is also a valid array index. At output position i, following the permutation twice gives nums[nums[i]]. Reading the original array while writing a separate result prevents earlier output values from changing later lookups.

Approach

Visit each value x in nums in its original order and append nums[x] to a new array. Since x is the original value at the current position, this is exactly the required double lookup. Return the new array after the scan. The input permutation stays unchanged.

class Solution: def buildArray(self, nums: List[int]) -> List[int]: ans = [] for x in nums: ans.append(nums[x]) return ans

Complexity analysis

Let n = nums.length. Time: O(n). The returned array uses O(n) space; auxiliary space excluding the output is O(1).