Today I practiced multiple array and loop-based problems to strengthen my fundamentals.
💻 Problems Covered
- Sum of array elements
- Find max & min in array
- Count even/odd numbers
- Reverse an array
- Remove duplicates
- Search a specific element
- Sliding window sum (basic idea)
- Subarray sum calculation
- Array rotation
🧠 Code Practice
// 1. Sum of array
let values = [1,2,3,4,5];
let result = 0;
for(let i = 0; i < values.length; i++){
result += values[i];
}
console.log(result);
// 2. Find max
values = [1,2,3,4];
let max = values[0];
for(let i = 0; i < values.length; i++){
if(values[i] > max){
max = values[i];
}
}
console.log(max);
// 3. Find min
values = [9,1,2,3,4];
let min = values[0];
for(let i = 0; i < values.length; i++){
if(values[i] < min){
min = values[i];
}
}
console.log(min);
// 4. Count even / odd
values = [9,1,2,3,4];
let even = 0;
let odd = 0;
for(let i = 0; i < values.length; i++){
if(values[i] % 2 === 0){
even++;
} else {
odd++;
}
}
console.log(even, odd);
// 5. Reverse array
values = [9,1,2,3,4];
let reversed = [];
for(let i = values.length - 1; i >= 0; i--){
reversed.push(values[i]);
}
console.log(reversed);
// 6. Remove duplicates
values = [9,1,4,1,2,3,4];
let unique = [];
for(let i = 0; i < values.length; i++){
if(!unique.includes(values[i])){
unique.push(values[i]);
}
}
console.log(unique);
// 7. Check if element exists
function findNumber(arr, num){
for(let i = 0; i < arr.length; i++){
if(arr[i] === num){
return true;
}
}
return false;
}
// 8. Sliding window sum (max sum)
values = [1,2,3,4];
let chunk = 3;
let maxSum = 0;
for(let i = 0; i <= values.length - chunk; i++){
let sum = 0;
for(let j = i; j < i + chunk; j++){
sum += values[j];
}
maxSum = Math.max(maxSum, sum);
}
console.log(maxSum);
// 9. Array rotation (right rotate)
values = [1,2,3,4,5];
for(let i = 0; i < 2; i++){
values.unshift(values.pop());
}
console.log(values);
🧠 What I Learned
- Basic array traversal using loops
- Difference between max/min logic
- Using nested loops for sliding window
- How array rotation works internally
- Importance of avoiding duplicate values
- Thinking in step-by-step logic
🔥 Key Takeaway
Most problems are just:
loop + condition + array manipulation
Once that pattern clicks, everything becomes easier.
💬 Note
Still learning, still improving.
Top comments (0)