Back to Top 5 (with.Java)
This is a post about the “Back to 5th” problem.
We’re going to go through 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_list | result |
---|---|
[12, 4, 15, 46, 38, 1, 14, 56, 32, 10] | [15, 32, 38, 46, 56] |
My solution to the problem
import java.util.*;
class Solution {
public int[] solution(int[] num_list) {
int[] answer = new int[num_list.length - 5];
Arrays.sort(num_list);
int idx = 0;
for(int i = 5; i < num_list.length; i++){
answer[idx++] = num_list[i];
}
} return answer;
}
Solution
int[] answer = new int[num_list.length - 5];: Create a new array answer in the existing array num_list to store the remaining elements minus the first five elements. The length of this array is set to num_list.length - 5.
Arrays.sort(num_list);: Sorts the input array num_list in ascending order. The sorted array is sorted from smallest to largest value.
int idx = 0;: Initialize the index variable idx for assigning values to the array answer.
for(int i = 5; i < num_list.length; i++) : Iterate over the input array num_list, starting at index 5 and repeating to the end. This ignores the first 5 elements and selects the element after the 5th.
answer[idx++] = num_list[i];: store the value at the current index i in a new array answer, incrementing the index idx to prepare it for storage at the next location.
return answer;: finally returns a new array answer with the selected elements.
This code sorts the input array, selects the remaining elements except for the first five, and returns them in a new array. The returned array stores the elements after the 6th in the sorted array.