Friday, July 11, 2025

Leetcode 1920 – Build Array from Permutation

  

Problem Statement:

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

Initial Code

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


Issues in the code


LineIssue
int[nums.length] numsnew; - Invalid Java syntax for array declaration.
 Should be: int[] numsnew = new int[nums.length];



Corrected code

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

No comments:

Post a Comment