Home > Software engineering >  distinct integers in JavaScript
distinct integers in JavaScript

Time:04-16

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]

    nums = [0,2,1,5,3,4]
var buildArray = function(nums) {
    return nums.map(n => nums[n]);
};
console.log(buildArray(nums))

can any one explain dry run of this and why it is giving output as shown above and what is distinct integers?

CodePudding user response:

What are distinct integers?

Simply means that all elements (integers) in the array are unique.

Explain the dry run of this and why is it giving output as shown above?

The description asks to build an array where each element is formed using the logic ans[i] = nums[nums[i]] which is achieved by nums.map(n => nums[n]) because for each element in nums, the callback passed to nums.map (Array.prototype.map) is called with three arguments, element, index, and a reference to the array. The last two arguments are not used in your code.

nums[n] is same as nums[nums[i]] because the first argument (n) is each element of the original array. ans[i] will be nums[nums[i]] because the callback returns nums[n] for each element and the length of the ans array is same as that of nums array.

For better understanding you can rewrite the code as follows:

const nums = [0, 2, 1, 5, 3, 4]

const buildArray = function(nums) {
  return nums.map((_, index) => nums[nums[index]]);
};

console.log(buildArray(nums))

CodePudding user response:

Maybe this example will help you understand what is going on in the code. All examples will produce same result. In the example using map, n is equivalent to nums[i].

const nums = [0, 2, 1, 5, 3, 4];

// Using Array.map()
var buildArray = function(nums) {
  return nums.map(n => nums[n]);
};
console.log('Using Array.map() : ', buildArray(nums))

// Using Array.map() with index
var buildArray2 = function(nums) {
  return nums.map((n, i) => nums[nums[i]]);
};
console.log('Using Array.map() with index : ', buildArray2(nums))

// Using For Loop
let ans = new Array(nums.length);
for (let i = 0; i < nums.length; i  ) {
  ans[i] = nums[nums[i]];
}
console.log('Using for loop : ', ans);

  • Related