Leetcode 1920: Build Array from Permutation

grid47
grid47
Exploring patterns and algorithms
Apr 29, 2024 4 min read

Given a zero-based permutation nums (0-indexed), build a new array ans of the same length where for each i, ans[i] = nums[nums[i]]. Return the array ans. A zero-based permutation means that the array consists of distinct integers from 0 to nums.length - 1 (inclusive).
Problem
Approach
Steps
Complexity
Input: The input consists of an array nums, which is a zero-based permutation of distinct integers from 0 to nums.length - 1.
Example: nums = [2, 0, 1, 4, 3]
Constraints:
• 1 <= nums.length <= 1000
• 0 <= nums[i] < nums.length
• The elements in nums are distinct.
Output: Return the array ans, where each element is nums[nums[i]].
Example: [1, 2, 0, 3, 4]
Constraints:
Goal: For each index i in the array nums, compute nums[nums[i]] and store it in the result array ans.
Steps:
• Iterate over the array nums.
• For each index i, compute ans[i] = nums[nums[i]].
• Return the resulting array ans.
Goal: Ensure that the algorithm handles arrays with lengths up to 1000.
Steps:
• The array length is at least 1.
• The elements are distinct and fall within the range 0 to nums.length - 1.
Assumptions:
• The input array is a valid zero-based permutation of integers.
• The length of the array will not exceed 1000.
Input: nums = [2, 0, 1, 4, 3]
Explanation: In the array nums = [2, 0, 1, 4, 3], the new array ans is computed as follows: ans[0] = nums[nums[0]] = nums[2] = 1, ans[1] = nums[nums[1]] = nums[0] = 2, ans[2] = nums[nums[2]] = nums[1] = 0, ans[3] = nums[nums[3]] = nums[4] = 3, ans[4] = nums[nums[4]] = nums[3] = 4. Thus, the final ans is [1, 2, 0, 3, 4].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus