I am trying to fix the one task from Coursera regarding Binary Search Algorithm. When I am testing my solution it works well. But the Autograder of Coursera is not accepting my solution and throwing that . What am I missing ?
Failed case #17/36: Wrong answer
(Time used: 0.06/5.00, memory used: 46239744/536870912.)
The task Input Format -- The first line of the input contains an integer n and a sequence a0 < a1 < ... < an−1 of n pairwise distinct positive integers in increasing order. The next line contains an integer k and k positive integers b0,b1,...,bk−1.
Constraints -- 1 ≤ n,k ≤ 10^4; 1 ≤ a[i] ≤ 10^9 for all 0 ≤ i < n; 1 ≤ b[]j ≤ 10^9 for all 0 ≤ j < k;
Output Format -- For all i from 0 to k−1, output an index 0 ≤ j ≤ n−1 such that aj = bi or −1 if there is no such index.
Sample 1.
Input:
5
1 5 8 12 13
5
8 1 23 1 11
Output:
2 0 -1 0 -1
In this sample, we are given an increasing sequence 𝑎0 = 1, 𝑎1 = 5, 𝑎2 = 8, 𝑎3 = 12, 𝑎4 = 13 of length five and five keys to search: 8, 1, 23, 1, 11. We see that 𝑎2 = 8 and 𝑎0 = 1, but the keys 23 and 11 do not appear in the sequence 𝑎. For this reason, we output a sequence 2, 0,−1, 0,−1.
My solution
function implemenetBinary(firstArray, secondArray) {
var locationArray = [];
for (let i = 0; i < secondArray.length; i++) {
let value = secondArray[i];
locationArray[i] = binarySearch(firstArray, value);
}
console.log(...locationArray);
return locationArray;
}
function binarySearch(arr, val) {
let start = 0;
let end = arr.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (arr[mid] === val) {
return mid;
}
if (val < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
var readline = require("readline");
process.stdin.setEncoding("utf8");
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
rl.on("line", readLine);
let inputLines = [];
function readLine(line) {
inputLines.push(line.toString().split(" ").map(Number));
if (inputLines.length == 4) {
implemenetBinary(inputLines[1], inputLines[3]);
}
}
Your binary search is fine.
Your input processing is broken on the empty lines you can get when n or k are 0.