#1920

Build Array from Permutation

Easy
ArraySimulationArrayIndex Mapping
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a single pass through the array to build the result, ensuring we only traverse the array once, which is efficient for larger inputs.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty array 'ans' of the same length as 'nums'.
  2. 2Step 2: For each index 'i' in 'nums', compute ans[i] = nums[nums[i]].
  3. 3Step 3: Return the 'ans' array.
solution.py4 lines
1# Full working Python code
2nums = [0, 2, 1, 5, 3, 4]
3ans = [nums[nums[i]] for i in range(len(nums))]
4print(ans)

Complexity note: This complexity is optimal because we only traverse the array once, resulting in linear time complexity.

  • 1The problem is a direct application of indexing, where the output is based on double indexing of the input array.
  • 2Understanding the properties of permutations helps in recognizing that each index will map to a unique value.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.