Why Runtime error if input array element are parsed to integer altogether in javascript?

I was working on counting sort1 problem on hackerrank. I am using JavaScript to solve the problem.

Standard input is providing a number and an array which I was reading like this

var inp = input.split('\n')  

var n = parseInt(inp[0]);  //Number of elements
var ar = inp[1].split(' ').map(function(item){
    return parseInt(item);
});   //Array of numbers.

I was using above code in almost all of my solutions, it always worked. Then I process the above array ar in for loop which is giving runtime error in one of the test cases(last testcase).

for(var i = 0; i < n; i++) {
   var number = ar[i];
   //more code

But if I don't parse elements of the array using map function but parse them later in for loop, one by one, I don't get any error.

var ar = in[1].split(' ');   //Array of numbers in string format

for(var i = 0; i < n; i++) {
   var number = parseInt(ar[i]);
   //more code

Can Anyone explain Why?



in is a keyword, and you are trying to use it as a variable. I'm not sure why it says "Runtime Error", since this is actually a parsing error. Once renamed to something else, I could run the first two paragraphs error-free.


The only problem I remember having on Hackerrank that the .split() method often gave an empty string ("") as the last element of the array. Probably that's why you failed on the last test case.

Make your logic like:

if(arr[i] !== "") 
    // perform operations

Also, you can't use in as a identifier because it is a reserved keyword.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.