JavaScript Coding Test Course, Taking Out Pebbles

Hello, everyone! In this blog post, we will take an in-depth look at the coding test algorithm problem “Taking Out Pebbles” using JavaScript. This problem will greatly help in understanding data structures and algorithms. Now, let’s define the problem.

Problem Definition

There is a bag containing several pebbles. Each pebble is numbered, and you need to extract pebbles that satisfy specific conditions. The pebbles are represented by n numbers, each of which represents the unique ID of that pebble.

Your task is to return the number of pebbles that are smaller than the given integer k when provided with the pebble array rocks and the integer k. The length of the array is from 1 to 1000, and each pebble’s ID is between 1 and 10,000.

For example:

  • Input: rocks = [5, 2, 8, 3, 6], k = 4
  • Output: 2 (Pebble IDs: 2, 3)

Problem-Solving Strategy

To solve this problem, we will use a basic array search technique. We will follow these steps to arrive at a solution.

1. Array Search

We will traverse the given array rocks and check if each pebble’s ID is smaller than k. If this condition is met, we will increase the count.

2. Return Count

After reviewing all the pebbles, we will finally return the count.

JavaScript Code Implementation

Now, let’s write a JavaScript function based on the above plan:

function countRocks(rocks, k) {
    let count = 0;
    for (let i = 0; i < rocks.length; i++) {
        if (rocks[i] < k) {
            count++;
        }
    }
    return count;
}

// Example usage
const rocks = [5, 2, 8, 3, 6];
const k = 4;
console.log(countRocks(rocks, k)); // Output: 2

Code Analysis

In the above code, the countRocks function takes two parameters: the rocks array and the k value. We initialize the count with let count = 0; and traverse the array using a for loop. If each pebble’s ID is smaller than k, we increase the count. Finally, we return the count.

Time Complexity Analysis

The time complexity for this problem is O(n). Since we check each element in the array only once, it has a linear time complexity.

Conclusion

Through today’s problem, “Taking Out Pebbles,” we laid the foundation of array searching and learned how to design efficient algorithms. Such problems will frequently appear in coding tests, playing a crucial role in building your fundamentals. I hope you also gain experience by solving various problems!

Practice Problem

Now it’s your turn to test your skills. Try to solve the following modified problem.

  • Modified Problem: Write a function to count the number of pebbles in the given rocks array that are greater than the value of k.

To solve this problem, you only need to change the condition. Think about what changes are needed in your code!