Skip to main content
Back to problems
Leetcode
Easy
Arrays
Build Array From Permutation

Construct a new array where each position takes its value from the index pointed to by the original array.

Acceptance 100%
Problem Statement

You are given a zero-based permutation array nums of length n, where each value in nums is an integer from 0 to n - 1 and appears exactly once.

Build a new array ans of length n such that for every index i,

ans[i] = nums[nums[i]].

Return the resulting array.

The task is a straightforward index-mapping transformation: use each value in the input array as an index into the same array and write down the referenced value in the output.

Input Format

  • The input is an integer array nums.
  • nums is a permutation of 0..n-1.
  • For every index i, compute ans[i] = nums[nums[i]].

Output Format

  • Return an integer array ans of the same length as nums.
  • ans[i] must equal the value at index nums[i] in the original array.

Constraints

  • 1 <= n <= 1000 or larger depending on platform test data.
  • nums contains each integer from 0 to n - 1 exactly once.
  • Do not assume values outside the valid index range.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

[0,1,2,4,5,3]

Explanation

For each index i, take nums[nums[i]]: [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] = [0,1,2,4,5,3].

Example 2

Input

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

Output

[4,5,0,1,2,3]

Explanation

Using the same rule, ans[0]=nums[5]=4, ans[1]=nums[0]=5, ans[2]=nums[1]=0, and so on.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.