DEV Community

King coder
King coder

Posted on • Edited on

DSA Problem Solving — Day 5 and 6

Welcome to Day 5 & 6 of my #DSAinJavaScript journey!
This week, I tackled a mix of string and array problems — each one sharpening core logic and edge case handling.

Here’s a quick breakdown with examples, approach, and code 🧠💻👇

✅ Problem 1: Count Negative Numbers in an Array

🔍 Problem:

Given an array, count how many numbers are negative.

📦 Example:


Input: [2, -9, 17, 0, 1, -10, -4, 8]
Output: 3

Enter fullscreen mode Exit fullscreen mode

🧠 Approach:

  • Loop through each element.
  • If it's less than 0, increase the counter.
  • Return the counter.

✅ Solution:

function countNegative(arr) {
  let counter = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < 0) counter++;
  }
  return counter;
}

Enter fullscreen mode Exit fullscreen mode

✅ Problem 2: Find the Largest Number in an Array

🔍 Problem:

Find the maximum value in a given array.

📦 Example:


Input: [4, 8, 7, 2, 17, 7, 3, 25, 8]
Output: 25


Enter fullscreen mode Exit fullscreen mode

🧠 Approach:

  • Start with -Infinity so even negative values are handled.
  • Loop through array, update if you find a larger number.

✅ Solution:

function findLargestNumber(arr) {
  let largest = -Infinity;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > largest) {
      largest = arr[i];
    }
  }
  return largest;
}


Enter fullscreen mode Exit fullscreen mode

ff

✅ Problem 3: Capitalize the Title

🔍 Problem:

Capitalize each word in a title based on length:

  • If word length ≤ 2 → lowercase.
  • Else → capitalize first letter, lowercase rest.

📦 Example:


Input: "First leTTeR of EACH Word"
Output: "First Letter of Each Word"


Enter fullscreen mode Exit fullscreen mode

🧠 Approach:

  • Use split(' ') to break the string.
  • Use map() to apply formatting based on length.

✅ Solution:

function capitalizeTitle(title) {
  return title
    .split(' ')
    .map(word => 
      word.length <= 2 
        ? word.toLowerCase() 
        : word[0].toUpperCase() + word.slice(1).toLowerCase()
    )
    .join(' ');
}

Enter fullscreen mode Exit fullscreen mode

✅ Problem 4: Reverse Words in a String III

🔍 Problem:

Reverse every word in a string without changing the word order.

📦 Example:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Enter fullscreen mode Exit fullscreen mode

🧠 Approach:

  • Split the string into words.
  • Reverse each word using split(''), reverse(), and join('').
  • Rejoin with ' '.

✅ Solution:

function reverseWords(s) {
  return s
    .split(' ')
    .map(word => word.split('').reverse().join(''))
    .join(' ');
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)