Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
distinct integers in JavaScript

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!