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

196
Views
HackerRank Plus Minus problem: Typescript

I am trying to solve the Plus Minus problem in HackerRank using Typescript. I am getting NaN as result in first two print statements, however, the last one is working. This is my solution:

function plusMinus(arr: number[]): void {
    // Write your code here
    
    let pos: number, neg: number, zero: number = 0; 
    
    for (let i=0; i< arr.length; i++){
        if(arr[i]>0){
            pos+=1; 
        }
        else if(arr[i]<0){
            neg+=1;
        }
        else{
            zero+=1; 
        }
    }
    let len: number = arr.length;
    let posRatio = (pos/len).toFixed(6);
    let negRatio = (neg/len).toFixed(6);
    let zeroRatio = (zero/len).toFixed(6); 
    
    console.log(posRatio);
    console.log(negRatio);
    console.log(zeroRatio);
    
}

Here is the output:

Compiler Message
Wrong Answer

Input (stdout)
6
-4 3 -9 0 4 1

Your Output (stdout)
NaN
NaN
0.166667

Expected Output

0.500000
0.333333
0.166667

Can anyone help me out to understand what the problem might have been?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

let pos: number, neg: number, zero: number = 0; 

You only defined a default value for zero in the above line. In JS (or TS), the default value of any variable is undefined unless you explicitly set one.

undefined + 1 is NaN.

console.log(undefined + 1)

Further reading

about 4 years ago · Santiago Gelvez Report

0

Issue is in your value initialization.

let pos: number, neg: number, zero: number = 0; 

If you would log this you will get

pos=undefined
neg=undefined
zero=0

and now if you try to add number with undefined it will give you NaN

Initialize pos, neg and zero to 0 properly.

about 4 years ago · Santiago Gelvez 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!