Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Edge case: Array sorting and parseInt in JavaScript.
Edge case: Array sorting and parseInt in JavaScript.
console.log([3, 20, 100].sort().join(","), [1, 2, 3].map(parseInt).join(","));What is printed?- A. 3,20,100 1,2,3
- B. 100,20,3 1,NaN,NaN
- C. 100,20,3 1,2,3
- D. 3,20,100 1,NaN,NaN
Correct answer: B. 100,20,3 1,NaN,NaN
Without a comparator, sort() compares values as strings, so '100' < '20' < '3'. map passes (value, index), so parseInt('1', 0) = 1, parseInt('2', 1) = NaN (radix 1 is invalid) and parseInt('3', 2) = NaN (3 is not a binary digit).
More Coding Interview Problems questions
- Problem: Answer sub-rectangle sum queries on a matrix in O(1) each with a 2-D prefix-sum table. python m = [[3, 0, 1, 4], [5, 6, 3, 2]…
- Problem: A van with fixed capacity picks up and drops passengers; trip [n, from, to] carries n passengers from km 'from' to km 'to' (they…
- Problem: Start at index 0 and finish at the last index; from i you may jump to any of i+1..i+k. Maximise the sum of visited values…
- Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute…
- Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to…
- Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find). python…