Contents

Back to 5th (with.Java)

   Nov 5, 2023     1 min read

This is a post about the “Back to 5th” problem.

We’re going to take a look at solving a coding test problem, reflect on the problem we solved, and learn about other ways to solve it.

Let’s start with the problem.

Problem

You are given a list num_list of integers.

Complete the solution function so that it returns a list containing the five smallest numbers in num_list in ascending order.

Example input and output
num_listresult
[12, 4, 15, 46, 38, 1, 14][1, 4, 12, 14, 15]

My solution to the problem

import java.util.*;

class Solution {
    public int[] solution(int[] num_list) {
        Arrays.sort(num_list);
        int[] answer = new int[5];
        for(int i = 0; i < 5; i++){
            answer[i] = num_list[i];
        }
    } return answer;
}
Solution

Arrays.sort(num_list);: Sorts the given array num_list in ascending order.

This sorts the numbers in the array from smallest to largest.

int[] answer = new int[5];: Creates an integer array answer of size 5.

This array will be used to store the five smallest numbers among the sorted numbers.

for(int i = 0; i < 5; i++) : Selects the first five numbers from the sorted array using a loop.

answer[i] = num_list[i];: Store the value of the current index i in the sorted array in the answer array.

return answer;: Returns the answer array with the five smallest numbers finally stored.

This code selects the five smallest numbers from the given array of integers and returns them, preserving their order.

Because it selects the first five numbers from a sorted array, the numbers returned are sorted in ascending order.