JavaScript Coding Test Course, Bubble Sort Program 2

Problem Description

Write a program that sorts a given integer array in ascending order. The elements of the array may include positive integers, negative integers, and zero. You must implement this using the basic sorting algorithm known as bubble sort.

Explanation of Bubble Sort Algorithm

Bubble sort is one of the simplest sorting algorithms, which sorts by comparing adjacent elements. This algorithm repeatedly traverses the array and compares two adjacent elements, swapping them if necessary. After traversing the array n times, the sorting is complete. In each iteration, the largest element bubbles up to the end of the array, hence the name ‘bubble sort.’

Working Process of Bubble Sort

  1. Let the length of the array be n, and perform n-1 iterations.
  2. In each iteration, traverse and compare the index i from 0 to n-1.
  3. Compare two adjacent elements, and if the left element is greater than the right element, swap them.
  4. This process consistently moves the maximum value to the end of the array.
  5. Repeat this process until sorting is complete.

Problem Solving Process

Step 1: Declare the Array

First, declare the array to be sorted. For example, we will use an array like the following.

let arr = [64, 34, 25, 12, 22, 11, 90];

Step 2: Write the Bubble Sort Function

Write a function named bubbleSort that implements bubble sort. This function takes an array as a parameter and returns the sorted array.


function bubbleSort(arr) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
    

Step 3: Call the Function and Output the Result

Call the function you wrote to check the result. The function can be called as follows, and the result is printed out.


let sortedArr = bubbleSort(arr);
console.log("Sorted Array:", sortedArr);
    

Complete Code Combination

The final code, combining all the processes, is as follows.


function bubbleSort(arr) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                let temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}

let arr = [64, 34, 25, 12, 22, 11, 90];
let sortedArr = bubbleSort(arr);
console.log("Sorted Array:", sortedArr);
    

Performance Analysis

The time complexity of bubble sort in the worst case is O(n2). This occurs because every element must be compared at least once. The average case also remains O(n2), and the best case (already sorted array) is O(n). Therefore, bubble sort can be efficient for small datasets, but it is not suitable for large data sets.

Conclusion

In this lesson, we learned how to sort an array using bubble sort. Although it’s a simple algorithm, one must be aware that repeatedly performing the same task can lead to performance degradation. Understanding such basic algorithms will serve as an important foundation when encountering more complex algorithms. In the next lesson, we will cover a more efficient sorting algorithm known as Quick Sort.

JavaScript Coding Test Course, Building Bridges

Problem Description

The bridge building problem is as follows. The given citizens want to build a bridge from ‘A’ to ‘B’.
This bridge will serve as a road connecting the two points ‘A’ and ‘B’ directly. Each citizen can choose several points to build the bridge,
and the distance between each point is predetermined. The problem is to find the length of the shortest bridge connecting the two points in the city.

Problem Input

– The first line contains the number of points n (1 ≤ n ≤ 1000).
– The second line contains an integer array positions representing the location of each point.

Problem Output

Output the minimum length required to build the bridge.

Example Input

    5
    1 2 4 5 10
    

Example Output

    9
    

Solution Process

The first step to solving this problem is to sort the positions of the given points.
The first point in the sorted list represents the location of ‘A’, and the last point represents the location of ‘B’.
This way, it will be easy to calculate the total distance that needs to be traveled to build the bridge.

Step 1: Input and Sorting


function buildBridge(positions) {
    // Sort the positions
    positions.sort((a, b) => a - b);
    return positions;
}
    

Step 2: Distance Calculation

The next step is to calculate the distance between the first and the last point.
This is the most important factor in determining the length of the bridge.


function calculateBridgeLength(positions) {
    const firstPoint = positions[0];
    const lastPoint = positions[positions.length - 1];
    return lastPoint - firstPoint;
}
    

Step 3: Complete Function Implementation

Now, finally, we will integrate the two implemented steps to complete the function that calculates the total length needed to build the bridge.


function buildBridge(positions) {
    // Sort the positions
    positions.sort((a, b) => a - b);
    
    // First and last points
    const firstPoint = positions[0];
    const lastPoint = positions[positions.length - 1];
    
    // Calculate bridge length
    return lastPoint - firstPoint;
}

// Example usage
const inputPositions = [1, 2, 4, 5, 10];
const bridgeLength = buildBridge(inputPositions);
console.log(bridgeLength);  // 9
    

Conclusion

Through this lecture, we practiced how to approach the given problem.
By organizing basic arrays and calculating lengths, we were able to obtain the desired output from the provided input.
This methodology is very useful for solving other algorithmic problems.
Try out more challenging problems in the future!

Future Learning References

  • Basic Data Structures and Algorithms: here
  • Solve Algorithm Problems Using JavaScript: here
  • Coding Test Preparation: here

JavaScript Coding Test Course, Finding Non-Square Numbers

Hello, everyone! Today, we will solve one of the coding test problems using JavaScript, which is the “Finding Non-Perfect Squares” problem. This problem is commonly encountered in developer interviews and requires an understanding of basic algorithmic thinking and the fundamental syntax of JavaScript.

Problem Description

Write a function that filters out and returns only the non-perfect square numbers from a given array of numbers.

A perfect square refers to a number that can be expressed as n*n for some integer n. For example, 1, 4, 9, 16, and 25 are, respectively, the squares of 1, 2, 3, 4, and 5.

Input and Output

  • Input: An array of integers (e.g., [1, 2, 3, 4, 5, 6])
  • Output: An array composed of non-perfect square numbers (e.g., [2, 3, 5, 6])

Examples

Input: [1, 2, 3, 4, 5, 6]
Output: [2, 3, 5, 6]
Input: [9, 10, 11, 12, 13, 14]
Output: [10, 11, 12, 13, 14]

Problem Solving Process

Step 1: Understand the Problem

First, let’s clarify the requirements to understand the problem. We will receive an array of integers and need to find the numbers that are not perfect squares from this array. To determine if a number is a perfect square, we can calculate the square root of each number and check whether it is an integer.

Step 2: Analyze the Examples

Let’s check which numbers are perfect squares using the given examples. For instance, in the array [1, 2, 3, 4, 5, 6], the perfect squares are 1 and 4. The remaining numbers 2, 3, 5, 6 are not perfect squares and should be included in the result array.

Step 3: Think of a Solution

We can use the following method to solve the problem:

  1. Iterate through each number and check if it is a perfect square.
  2. If a number exists such that n*n equals the integer n, then that number is a perfect square.
  3. Add the non-perfect square numbers to a new array.
  4. Finally, return the new array.

Step 4: Implement the Code

Based on the methods discussed above, let’s write the JavaScript code.

function isPerfectSquare(num) {
    const sqrt = Math.sqrt(num);
    return sqrt === Math.floor(sqrt);
}

function findNonPerfectSquares(arr) {
    return arr.filter(num => !isPerfectSquare(num));
}

// Example tests
console.log(findNonPerfectSquares([1, 2, 3, 4, 5, 6])); // [2, 3, 5, 6]
console.log(findNonPerfectSquares([9, 10, 11, 12, 13, 14])); // [10, 11, 12, 13, 14]

Step 5: Explain the Code

In the code above, we defined two functions:

  • isPerfectSquare(num): This function checks whether the given number is a perfect square. It computes the square root and compares it with the original number after removing the decimal part.
  • findNonPerfectSquares(arr): This function filters out the non-perfect square numbers from the given array and returns them as a new array. It uses the Array.filter() method to find the non-perfect squares.

Step 6: Consider Performance

The time complexity of this code is O(n). Since we check each element of the array once, the performance depends linearly on the length of the array in the worst case. This algorithm is efficient enough and should perform well in real-world problems.

Step 7: Handle Various Test Cases

Finally, let’s utilize additional test cases to solve this problem:

  • Edge case: What should be the output for an empty array []? – It should return an empty array [].
  • Including negative numbers: For [-1, -4, 3, 8], the non-perfect squares are -1, 3, 8.
  • Changing array: For [0, 1, 2, 3, 16, 25], the non-perfect squares are [2, 3].

Conclusion

Today, we solved the “Finding Non-Perfect Squares” problem. Through this problem, we gained an understanding of basic array processing and the mathematical concept of perfect squares. We learned how to solve problems using the fundamental syntax of JavaScript and array methods.

While preparing for coding tests, it is essential to practice various types of problems. By solving multiple problems, you can establish a fundamental understanding of algorithms and improve your problem-solving skills. In the next lesson, we will tackle even more interesting problems!

Thank you!

JavaScript Coding Test Course, Finding the Minimum Number of Coins

Author: [Author Name]

Written on: [Written Date]

Problem Description

This is a problem of calculating the minimum number of coins needed to make change. You need to find a way to make the total amount using the minimum number of coins based on the given denominations and total amount. Assume that there are an infinite number of each type of coin.

For example, if you have coin denominations of {1, 5, 10, 25} and the total amount to be made is 63, you need to determine the minimum number of coins required.

Input

  • coinValues: An integer array representing the types of coins (e.g., [1, 5, 10, 25])
  • amount: An integer representing the total amount (e.g., 63)

Output

  • Returns the minimum number of coins. If it is not possible to make the amount, return -1.

Problem Approach

This problem can be solved using dynamic programming. Dynamic programming involves breaking the problem down into smaller subproblems and combining the solutions to these subproblems to find the solution to the overall problem. To solve this problem, we will follow these steps.

  1. Initialize the DP table: Create a DP table to record the minimum number of coins needed for each amount that can be made using the coins.
  2. Set base case: The 0th index of the DP table (0 dollars) does not require any coins, so it is set to 0.
  3. Utilize previous results: For each coin, calculate the possible amounts and update the DP table.
  4. Return result: The lowest number of coins to make the required amount, or -1 if it’s impossible.

JavaScript Code Implementation


function coinChange(coinValues, amount) {
    // Initialize DP Table
    const dp = Array(amount + 1).fill(Infinity);
    dp[0] = 0; // The number of coins to make 0 dollars is 0

    // Check each coin one by one
    for (let coin of coinValues) {
        for (let j = coin; j <= amount; j++) {
            dp[j] = Math.min(dp[j], dp[j - coin] + 1);
        }
    }

    // Return result
    return dp[amount] === Infinity ? -1 : dp[amount];
}

            

This code creates a DP table using the given coinValues array and amount, then calculates the minimum number of coins required.

Description of Process

The above code consists of several steps, which we will explore to minimize the number of coins.

Step 1: Initialize DP Table

const dp = Array(amount + 1).fill(Infinity); This line creates an array of a fixed length and initializes all values to infinity.
Then, dp[0] = 0; sets the number of coins needed to make 0 dollars to 0.

Step 2: Update Amount for Each Coin

for (let coin of coinValues) iterates through each coin to calculate the possible amounts.
In the nested for loop, dp[j] = Math.min(dp[j], dp[j - coin] + 1); updates the minimum number of coins for each amount.

Step 3: Return Result

Finally, return dp[amount] === Infinity ? -1 : dp[amount]; returns -1 if the amount cannot be made. If it can be made, it returns the minimum number of coins.

Examples and Test Cases

Example 1

Input: coinValues = [1, 5, 10, 25], amount = 63

Output: 6

Explanation: A total of 6 coins are used to make 63: 25, 25, 10, 1, 1, 1.

Example 2

Input: coinValues = [2], amount = 3

Output: -1

Explanation: It is not possible to make 3 using only 2.

Example 3

Input: coinValues = [1], amount = 0

Output: 0

Explanation: No coins are needed to make 0 dollars.

Time Complexity and Space Complexity of This Code

The time complexity of this algorithm is O(n * m), where n is the number of coin types and m is the target amount. The complexity arises because updating and creating the DP table involves O(m) operations repeated for each coin.
The space complexity is O(m) due to the dynamically created DP table for the number of coins.

Conclusion

This article discussed how to solve the problem of finding the minimum number of coins using dynamic programming with JavaScript.
After presenting the problem, we explored various solutions and code implementations in depth.
Such algorithms are frequently encountered in actual interviews, so it is advisable to learn them well.
I hope this helps you in your future coding test preparations!

JavaScript Coding Test Course, Sum of Numbers

This article will cover one of the frequently asked algorithm problems in JavaScript coding tests, “Sum of Digits.” Through this problem, we will learn about basic algorithm construction abilities and how to handle data in JavaScript.

Problem Description

Given a string of numbers, write a function that calculates the sum of the digits included in the string.
For example, if the input string is “12345”, it should return 1 + 2 + 3 + 4 + 5 = 15.

Input

  • A single string of digits with length n is provided (1 ≤ n ≤ 106)

Output

  • Returns the sum of all the digits in the string as an integer.

Problem Approach

To solve this problem, the following basic steps will be undertaken:

  1. Traverse the string of digits and convert each character to a number.
  2. Accumulate the converted numbers.
  3. Return the final sum.

Code Implementation

The code implementation to solve this problem in JavaScript can be done as follows.


function sumOfDigits(numString) {
    // Initialize basic variable
    let total = 0;

    // Traverse characters
    for(let i = 0; i < numString.length; i++) {
        // Convert each character to number and accumulate
        total += parseInt(numString[i]);
    }

    // Return final sum
    return total;
}

// Function test
const inputString = "12345";
const result = sumOfDigits(inputString);
console.log("Input string:", inputString);
console.log("Sum of digits:", result); // Output: 15

Code Explanation

The above code defines a function called sumOfDigits. This function takes a string of numbers as input, traverses each character, converts it to an integer, and calculates the total sum.

  • let total = 0;: Initializes a variable to store the sum from the string.
  • for(let i = 0; i < numString.length; i++) { ... }: Uses a loop to iterate through each character of the input string based on its length.
  • total += parseInt(numString[i]);: Uses parseInt to convert each character of the string to an integer and accumulates the sum.
  • return total;: Returns the accumulated sum.

Time Complexity Analysis

The time complexity of this algorithm is O(n), where n refers to the length of the input string. Since we only traverse the string once, the time complexity is linear.

Space Complexity Analysis

The space complexity is O(1). This is because, apart from the input string, only one additional variable is used.

Variant Problem

If the above problem is the basic form, a variant might be "Calculate the sum of positive numbers in an array containing both negative and positive numbers."
Such problems may require adjusting the basic algorithm or considering additional conditions, thus necessitating slight modifications to the code.

Example Modified Code for Variant Problem


// Variant Problem: Calculate the sum of digits at even indices
function sumEvenIndexedDigits(numString) {
    let total = 0;

    // Sum only the digits at even indices
    for(let i = 0; i < numString.length; i += 2) {
        total += parseInt(numString[i]);
    }
    
    return total;
}

// Code test
const inputString = "123456"; // Example: sum 1, 3, and 5
console.log("Sum of even indices:", sumEvenIndexedDigits(inputString)); // Output: 12

Conclusion

The "Sum of Digits" problem is very useful for learning the basic syntax and algorithms of JavaScript.
Through this problem, one can learn foundational concepts like string handling, loops, and conditional statements.
Try exploring various variant problems to deepen your understanding of algorithms.

In the next session, we will tackle more complex problems. I hope this course helps you learn various techniques that you can use in JavaScript coding tests and aids you in effectively solving problems.