Build Array from Permutation - 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.

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

Input & Output

Example 1 — Basic Permutation
$ Input: nums = [0,2,1,5,3,4]
Output: [0,1,2,4,5,3]
💡 Note: ans[0] = nums[nums[0]] = nums[0] = 0, ans[1] = nums[nums[1]] = nums[2] = 1, ans[2] = nums[nums[2]] = nums[1] = 2, and so on.
Example 2 — Simple Case
$ Input: nums = [5,0,1,2,3,4]
Output: [4,5,0,1,2,3]
💡 Note: ans[0] = nums[5] = 4, ans[1] = nums[0] = 5, ans[2] = nums[1] = 0, creating a shifted pattern.
Example 3 — Minimum Size
$ Input: nums = [0]
Output: [0]
💡 Note: Single element case: ans[0] = nums[nums[0]] = nums[0] = 0.

Constraints

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

Visualization

Tap to expand
Build Array from Permutation INPUT nums array (0-indexed) i=0 i=1 i=2 i=3 i=4 i=5 0 2 1 5 3 4 Goal: ans[i] = nums[nums[i]] ans[0] = nums[nums[0]] = nums[0] = 0 ans[1] = nums[nums[1]] = nums[2] = 1 ans[3] = nums[nums[3]] = nums[5] = 4 n = 6, values: 0 to 5 ALGORITHM STEPS 1 Mathematical Encoding Store 2 values in 1 cell new = old + (new_val % n) * n 2 First Pass: Encode nums[i] += (nums[nums[i]] % n) * n Encoded Values (n=6) i=0: 0+(0%6)*6 = 0+0 = 0 i=1: 2+(1%6)*6 = 2+6 = 8 i=2: 1+(2%6)*6 = 1+12 = 13 i=3: 5+(4%6)*6 = 29 i=4: 3+(5%6)*6 = 33 i=5: 4+(3%6)*6 = 22 [0, 8, 13, 29, 33, 22] 3 Second Pass: Decode nums[i] = nums[i] / n 4 Extract New Values Integer division gives result O(n) time, O(1) space FINAL RESULT After decoding (divide by n=6): 0 / 6 = 0 8 / 6 = 1 13 / 6 = 2 29 / 6 = 4 33 / 6 = 5 22 / 6 = 3 Output Array 0 1 2 3 4 5 0 1 2 4 5 3 ans = [0, 1, 2, 4, 5, 3] OK - Verified! Verification: ans[0]=nums[0]=0 ans[1]=nums[2]=1 ans[3]=nums[5]=4 Key Insight: Since values are in range [0, n-1], we can encode TWO values in one cell using: encoded = old + (new % n) * n To decode: old_value = encoded % n, new_value = encoded / n. This achieves O(1) space without extra array! TutorialsPoint - Build Array from Permutation | In-Place Mathematical Encoding Approach
Asked in
LeetCode 15 Google 8
60.9K Views
Medium Frequency
~5 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen