Count Negative Numbers

Read
Count Negative Numbers

Counting Negative Numbers in an Array (JavaScript & Python)#

Kabhi-kabhi problems dekhne me kaafi simple lagti hain, lekin jab hum actually code likhne baithte hain, tab chhoti-chhoti cheezein confuse kar deti hain.
Counting negative numbers in an array bhi aisi hi ek problem hai.

Is blog me hum:

  • problem ko simple language me samjhenge

  • logic ko pehle words me break karenge

  • phir JavaScript aur Python dono me solution likhenge

  • aur end me thoda interview + real-project angle bhi dekhenge

Problem Statement (Simple Words)#

Hume ek array diya gaya hai.
Array ke andar positive, zero ya negative numbers ho sakte hain.

- Hume sirf ye count karna hai ki kitne numbers negative hain.

Example:#

Input:  [2, -5, 6, -1, 0, -8]
Output: 3

Kyunki negative numbers hain: -5, -1, -8

Pehle Soch Samajh Le (Before Code)#

Code likhne se pehle ye questions clear hone chahiye:

  1. Agar input array hi na ho to?

  2. Agar array ke andar number ke alawa kuch aur ho?

  3. NaN aur Infinity jaise values ka kya?

Real projects aur interviews me input validation bahut important hota hai, isliye hum yahan thoda strict approach lenge.

Core Logic (Plain English)#

Chal bina code ke logic samajhte hain:

  1. Sabse pehle check karo ki input ek array hai ya nahi

  2. Agar array nahi hai → invalid input

  3. Ab array ke har element ko ek-ek karke dekho

  4. Agar koi value proper number nahi hai → invalid input

  5. Jo values 0 se chhoti hain, unka count badhate jao

  6. End me total count return kar do

Bas. Logic itna hi hai

Important Edge Cases#

Ye cases ignore karoge to tests ya interview me problem aa sakti hai:

  • Input array nahi hai (string, number, null)

  • Array me "5" jaise strings aa gaye

  • NaN, Infinity, -Infinity

  • Empty array (ye valid case hai, output 0 hona chahiye)

JavaScript Solution#

JavaScript Code (Clean & Safe)#

18 lines
function countNegatives(arr) {
  // Check: input array hai ya nahi
  if (!Array.isArray(arr)) return false;

  // Validate each value
  for (let val of arr) {
    if (typeof val !== "number" || !Number.isFinite(val)) {
      return false;
    }
  }

  // Count negative numbers
  return arr.filter(num => num < 0).length;
}

// Example
console.log(countNegatives([2, -5, 6, -1, 0, -8])); // 3

Yahan kya ho raha hai?#

  • for...of loop → array ke har element ko direct access karta hai

  • Number.isFinite() → NaN aur Infinity ko reject karta hai

  • filter() → sirf negative numbers nikal leta hai

Python Solution#

Python me logic almost same hi rahega, bas syntax change hoga.

25 lines
def count_negatives(arr):
    # Check if input is a list
    if not isinstance(arr, list):
        return False

    count = 0

    for val in arr:
        # Check if value is int or float
        if not isinstance(val, (int, float)):
            return False

        # NaN check
        if val != val:
            return False

        if val < 0:
            count += 1

    return count


# Example
print(count_negatives([2, -5, 6, -1, 0, -8]))  # 3

Python me NaN check kyun alag hai?#

Python me:

NaN != NaN

Isliye val != val se hum NaN detect kar lete hain.

Common Mistakes (Jo Maine Khud Ki)#

  • Sirf typeof === "number" check karna (JS me NaN bhi number hota hai)

  • Input validation ko ignore kar dena

  • Direct logic likhna bina edge cases soche

  • Tests me “reject invalid input” ka matlab galat samajhna

Interview Perspective#

Agar interviewer pooche:

“How will you solve this problem?”

Tu simple words me bol sakta hai:

Main pehle input validate karta hoon.
Uske baad array ke har element ko check karta hoon.
Jo values valid numbers hain aur zero se chhoti hain, unka count karta hoon.
End me total negative numbers return karta hoon.

Possible Follow-up Questions:#

  • NaN ko number hone ke bawajood reject kyun kiya?

  • Time complexity kya hai?

  • Loop vs filter — kaunsa better hai aur kyun?

Real Project Connection#

Ye concept real life me kaafi jagah use hota hai:

  • Form input validation

  • API response clean karna

  • Dashboard me wrong numeric data filter karna

  • Analytics / reports me negative values count karna

📌 Final Thought#

Problem simple thi, lekin input validation ne usse real-world problem bana diya.

Rahul Verma

Full Stack Developer passionate about building modern web applications. Sharing insights on React, Next.js, and web development.

Learn more about me

Enjoyed this article?

Check out more articles on similar topics in the blog section.

Explore More Articles