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
🧠 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;
}
✅ 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
🧠 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;
}
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"
🧠 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(' ');
}
✅ 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"
🧠 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(' ');
}
Top comments (0)