↓Skip to main content
  1. LeetCode/

LeetCode 1920: Build Array from Permutation

·1 min· ·
LeetCode Easy Array Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-05-06

  • Submissions: Accepted (first try)

Approach
#

Build the new array by definition (Array Template 5). For the O(1) extra-space follow-up, values lie in 0..n-1, so each slot can hold two: nums[i] += n * (nums[nums[i]] % n); % n recovers the old value and // n the new one.

My Solution
#

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

Complexity
#

Time O(n), space O(n) for the output.

Mistakes to Avoid
#

  • When working in place, read old values with % n, since earlier slots may already be modified.

Interview Explanation
#

Building ans[i] = nums[nums[i]] directly is enough. In place, since values are below n, add the new value times n onto each slot and divide by n at the end. Time O(n).

Related

LeetCode 3507: Minimum Pair Removal to Sort Array I
·2 mins
LeetCode Easy Simulation Array
LeetCode 3507 note: n is tiny, so simulate; the right side of a slice assignment must be a list
LeetCode 3069: Distribute Elements Into Two Arrays I
·1 min
LeetCode Easy Array Two-Pointers Simulation
LeetCode 3069 note: simulate the rule: the first two go to separate arrays, then each element joins the array whose last element is larger
LeetCode 682: Baseball Game
·1 min
LeetCode Easy Array Stack Simulation
LeetCode 682 note: keep valid scores on a stack; C removes the last, D adds its double, and + adds the sum of the last two
LeetCode 1646: Get Maximum in Generated Array
·2 mins
LeetCode Easy Array Simulation
LeetCode 1646 note: generate by the rules, nums[i // 2] at even i and nums[i // 2] + nums[i // 2 + 1] at odd i, handling n = 0 separately
LeetCode 867: Transpose Matrix
·1 min
LeetCode Easy Array Matrix Simulation
LeetCode 867 note: the transpose is n × m with res[j][i] = matrix[i][j]; in Python, zip(*matrix)
LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)