Array-Based Coding Problems
You have learned a lot about arrays: creating them, looping through them, and using methods like map, filter, reduce, and sort. Now it's practice time! 💪
Learning to code is like learning to ride a bicycle 🚲. Reading about it helps a little, but you only get better by actually riding. The same is true for coding problems.
How to Use This Lesson
For every problem:
- 📖 Read the problem and the example carefully.
- 🤔 Think about how you would solve it on paper first.
- ⌨️ Try writing your own code in the playground.
- ✅ Then check the solution and the explanation.
Don't worry if you can't solve a problem on the first try. Even experienced developers get stuck. What matters is that you try first. 🙌
A Simple Plan for Solving Any Problem
| Step | Ask yourself |
|---|---|
| 1. Understand | What is the input? What should the output be? |
| 2. Example | Can I solve a small example by hand? |
| 3. Plan | What steps did I follow by hand? |
| 4. Code | Can I turn those steps into code? |
| 5. Test | Does it work for empty arrays, one item, or duplicates? |
🟢 Level 1: Easy
Problem 1: Sum and Average
Task: Find the total and the average marks of a student.
Input: [78, 85, 92, 66, 74]Output: Sum: 395, Average: 79
💡 Idea: Add all the numbers, then divide the sum by how many numbers there are.
Problem 2: Largest and Smallest Number
Task: Find the highest and the lowest score in a cricket series.
Input: [45, 110, 82, 23, 67]Output: Max: 110, Min: 23
💡 Idea: Start by assuming the first number is both the biggest and the smallest. Then check every number and update if you find a bigger or smaller one.
Problem 3: Count Even and Odd Numbers
Input: [1, 2, 3, 4, 5, 6, 7]Output: Even: 3, Odd: 4
💡 Idea: A number is even if dividing it by 2 leaves no remainder (n % 2 === 0).
Problem 4: Reverse an Array (Without reverse())
Input: [1, 2, 3, 4, 5]Output: [5, 4, 3, 2, 1]
💡 Idea: Swap the first and last items, then move inward from both sides. It's like two people standing at the two ends of a line and walking towards each other, swapping places each step. This is called the two-pointer technique.
[1, 2, 3, 4, 5]
↑ ↑ swap 1 and 5 → [5, 2, 3, 4, 1]
↑ ↑ swap 2 and 4 → [5, 4, 3, 2, 1]
↑ they meet → stop ✅
Problem 5: Check if an Item Exists
Task: Check if a city is on the delivery list.
Input: ["Delhi", "Pune", "Jaipur"], search: "Pune"Output: Pune is available ✅
💡 Idea: Go through each item. If it matches, stop and say "found."
🟡 Level 2: Medium
Problem 6: Remove Duplicates
Task: Remove repeated drinks from an order list.
Input: ["Tea", "Coffee", "Tea", "Juice", "Coffee"]Output: ["Tea", "Coffee", "Juice"]
💡 Idea: Keep an item only the first time you see it.
A
Setis a special collection that stores only unique values. Converting an array to a Set automatically removes duplicates.
Problem 7: Count How Often Each Item Appears
Task: Count the votes for each snack at a class party. 🍿
Input: ["Samosa", "Pizza", "Samosa", "Momos", "Pizza", "Samosa"]Output: { Samosa: 3, Pizza: 2, Momos: 1 }
💡 Idea: Use an object like a tally sheet. Every time you see a snack, add 1 to its count.
How (count[snack] || 0) + 1 works:
- First time we see "Samosa" →
count["Samosa"]isundefined→undefined || 0gives0→0 + 1 = 1 - Next time →
count["Samosa"]is1→1 + 1 = 2
Problem 8: Find the Second Largest Number
Input: [10, 45, 32, 45, 28]Output: 32
💡 Idea: Keep track of the top two numbers while going through the list once. Be careful: 45 appears twice, but the second largest is still 32.
Another way (simpler, but slower for big arrays):
Problem 9: Find the Missing Number
Task: Roll numbers from 1 to 6 should be present, but one student is absent. Find the missing roll number.
Input: [1, 2, 4, 5, 6]Output: 3
💡 Idea: The sum of numbers from 1 to n is n × (n + 1) ÷ 2. Find what the sum should be, subtract what it actually is, and the difference is the missing number! 🧠
Problem 10: Move All Zeros to the End
Input: [0, 1, 0, 3, 12]Output: [1, 3, 12, 0, 0]
💡 Idea: Separate the non-zero numbers and the zeros, then put them back together. The order of the non-zero numbers must stay the same.
Problem 11: Find Common Items in Two Arrays
Task: Find the friends who are coming to both parties. 🎉
Input: ["Amit", "Neha", "Ravi", "Sara"] and ["Ravi", "Kiran", "Amit"]Output: ["Amit", "Ravi"]
💡 Idea: Keep only the items from the first list that are also in the second list.
Problem 12: Split an Array into Groups (Chunks)
Task: Divide students into teams of 2 for a project.
Input: ["A", "B", "C", "D", "E"], team size: 2Output: [["A", "B"], ["C", "D"], ["E"]]
💡 Idea: Jump forward by the team size each time, and slice() out one group.
🔴 Level 3: Interview Favourites
Problem 13: Two Sum ⭐
Task: Find the positions of two numbers that add up to a target.
Input: nums = [2, 7, 11, 15], target = 9Output: [0, 1] (because 2 + 7 = 9)
This is one of the most famous coding interview questions!
Approach 1: Check every pair (simple, but slow)
💡 Idea: Try every possible pair of numbers.
This works, but for 1,000 numbers it checks about 500,000 pairs! 🐢
Approach 2: Remember what you've seen (fast)
💡 Idea: For each number, ask: "Have I already seen the number I need to reach the target?" Keep a notebook (an object) of numbers you've seen, and where you saw them.
target = 9
see 2 → need 7 → not seen yet → note down: { 2: 0 }
see 7 → need 2 → seen at index 0! ✅ → answer [0, 1]
This checks each number only once. 🚀
Problem 14: Rotate an Array
Task: Rotate the array to the right by k steps.
Input: [1, 2, 3, 4, 5], k = 2Output: [4, 5, 1, 2, 3]
💡 Idea: Take the last k items and move them to the front. Like a merry-go-round 🎠: each step, the last seat comes around to the front.
Problem 15: Merge Two Sorted Arrays
Input: [1, 4, 7] and [2, 3, 8]Output: [1, 2, 3, 4, 7, 8]
💡 Idea: Imagine two queues, both sorted by height. Compare the front person in each queue, and send the shorter one forward first. Repeat until both queues are empty.
Problem 16: Maximum Profit from Stock Prices 📈
Task: You are given the price of a stock for each day. Buy on one day and sell on a later day. Find the maximum profit.
Input: [7, 1, 5, 3, 6, 4]Output: 5 (buy at 1, sell at 6)
💡 Idea: Go day by day. Remember the lowest price seen so far. On each day, check: "If I sell today, how much profit would I make?"
Problem 17: Maximum Sum of a Continuous Part (Kadane's Algorithm)
Task: Find the largest sum of any continuous part of the array.
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]Output: 6 (from the part [4, -1, 2, 1])
💡 Idea: Walk through the array, keeping a running total. If the running total becomes negative, it will only pull the next numbers down, so start fresh from the next number.
It's like a road trip 🚗: if you've lost more than you've gained so far, forget the past and restart the journey from here.
🎯 Practice Challenges (Try Yourself!)
No solutions here. Use the playground and try them on your own! 💪
- Is it sorted? Check if an array is in ascending order. (Hint:
every()) - Product of all numbers: Multiply all the numbers in an array. (Hint:
reduce()starting with1) - Longest word: Find the longest word in
["Delhi", "Thiruvananthapuram", "Goa"]. - Group by first letter:
["apple", "avocado", "banana", "blueberry"]→{ a: [...], b: [...] } - Running total:
[1, 2, 3, 4]→[1, 3, 6, 10] - Find all pairs that add up to 10 in
[1, 9, 3, 7, 5, 5]. - Leaders: Find all numbers that are bigger than every number to their right in
[16, 17, 4, 3, 5, 2]→[17, 5, 2].
Common Patterns You Just Learned
| Pattern | Used in | Idea |
|---|---|---|
| Running total | Sum, average, max profit | Keep updating one value while looping |
| Track the best | Max/min, second largest | Remember the best value seen so far |
| Tally sheet (object) | Count items, two sum | Store what you have seen in an object |
| Two pointers | Reverse, merge sorted | Move two positions towards each other or side by side |
| Set | Remove duplicates | A collection of unique values |
| Maths trick | Missing number | Use a formula instead of a loop |
Tips for Solving Array Problems
- ✅ Always test with edge cases: an empty array
[], one item[5], negative numbers, and duplicates. - ✅ Write a simple solution first, even if it's slow. Make it faster later.
- ✅ Use clear variable names like
highest,total, andseen, notxortemp. - ✅ Use
console.log()inside loops to see what is happening at each step. - ✅ Practice a little every day. Consistency beats a long session once a week. 🚀
Key Takeaways
- Solving problems is the best way to master arrays. Try first, then check the solution.
- Most array problems use a few common patterns: running totals, tracking the best value, tally objects, two pointers, and Sets.
reduce()is great for totals and counts, whilefilter(),includes(), andSetmake many problems short and simple.- A slow solution that works is a great start. Then look for a faster idea, like in Two Sum.
- Break every problem into small steps, and solve them one at a time. 🧩