#1920

Build Array from Permutation

Easy Index mapping

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Given a permutation nums of 0..n-1, return ans where ans[i] = nums[nums[i]].

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: ans[i] = nums[nums[i]] — follow the pointer once.

Why this works: the simple version builds a new array. The in-place version stores two values in one slot (old + n × new), then divides by n.

Example: nums = [0, 2, 1, 5, 3, 4]

i=0: nums[0]=0 → nums[0]=0i=1: nums[1]=2 → nums[2]=1i=3: nums[3]=5 → nums[5]=4ans = [0, 1, 2, 4, 5, 3]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Doing the in-place update without % n, which reads already-modified values.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1) extra for the in-place version.