{x}
blog image

Build Array from Permutation

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).

 

Example 1:

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:

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

This problem asks to create a new array ans where ans[i] = nums[nums[i]]. This means we're using the value at each index of nums as an index into nums again to get the corresponding value for ans.

Approach

The most straightforward approach is to iterate through the input array nums and, for each element, use it as an index to access the element in nums again. This resulting value is then placed in the corresponding index of the output array ans.

Code Implementation (Python)

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

This code iterates through nums using a for loop. Inside the loop, nums[nums[i]] directly computes the element for ans[i]. The computed element is added to the ans list. Finally, the ans list is returned.

A more concise Python solution using list comprehension:

class Solution:
    def buildArray(self, nums: List[int]) -> List[int]:
        return [nums[i] for i in nums]

This single line achieves the same result more efficiently.

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the input array nums. We iterate through the array once to build the ans array.
  • Space Complexity: O(n). We create a new array ans of the same size as nums to store the result. If we disregard the space used for the output array, the space complexity becomes O(1) as we only use a constant amount of extra space during computation.

Code Implementation in Other Languages

The solution is similar in other languages, mainly differing in syntax. Here are examples in a few other languages:

Java:

class Solution {
    public int[] buildArray(int[] nums) {
        int[] ans = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            ans[i] = nums[nums[i]];
        }
        return ans;
    }
}

C++:

class Solution {
public:
    vector<int> buildArray(vector<int>& nums) {
        vector<int> ans;
        for (int i = 0; i < nums.size(); ++i) {
            ans.push_back(nums[nums[i]]);
        }
        return ans;
    }
};

JavaScript:

var buildArray = function(nums) {
    let ans = [];
    for (let i = 0; i < nums.length; i++) {
        ans.push(nums[nums[i]]);
    }
    return ans;
};

The core logic remains consistent across all languages: iterating through the input array and using its elements as indices to create the output array. The time and space complexities remain the same.