HackerRank Tests and Answers

Makori
2 min readNov 4, 2023

--

I have 5 years experience as a software developer, and I can attest hackerRank tests are the worst! They have more that 12 cases, some of which are hidden, which makes it extremely difficult to debug the code and make sure all the test cases run. However, over the years, I have understood what the edgy cases entail, one of which is code optimization. Your program must execute in less than 10 seconds for all the test cases to run!! This is why I love writing my code in Python or Java.

This is one of the sample questions that has been challenging over the years;

A student is taking a test on n different subjects. For
each i th subject they have already answered
answered[i] questions and have time to answer a total
of q more questions overall. For each i th subject, the
number of questions answered has to be at least
needed{i] in order to pass. Determine the maximum
number of subjects the student can pass if the
q additional answered questions are optimally
distributed among the subjects.
For example, there are n = 2 subjects and needed = {4,
5] answered questions, respectively, to pass. The
student has answered answered = [2, 4] questions in
the two subjects so far, and can answer another q =
I questions in all subjects combined. The best
outcome is to answer an additional question in the
second subject to pass it, and it is not possible to pass
the first subject. The maximum number of subjects
that can be passed is T.
Function Description
Complete the function maxSubjectsNumber in the
editor below. The function must return an integer that
represents the maximum number of subjects that can
be passed.
maxSubjectsNumber has the following parameter(s):
answered{answered[0],… answered[n-7]j: an array
of integers
an array of
integers
q. an integer

constraints
1<n<10 raised to power 5
0<=answered[i], needed[i], q<=10 raised to power 9

Solution:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SubjectInfo {
int diff;
int idx;

SubjectInfo(int diff, int idx) {
this.diff = diff;
this.idx = idx;
}
}

public class Main {
public static int maxSubjectsNumber(int[] answered, int[] needed, int q) {
List<SubjectInfo> diffList = new ArrayList<>();

for (int i = 0; i < answered.length; i++) {
int diff = Math.max(0, needed[i] - answered[i]);
diffList.add(new SubjectInfo(diff, i));
}

Collections.sort(diffList, Comparator.comparingInt(s -> s.diff));

int subjectsPassed = 0;

for (SubjectInfo subjectInfo : diffList) {
int diff = subjectInfo.diff;
int idx = subjectInfo.idx;

if (q >= diff) {
q -= diff;
subjectsPassed++;
} else {
break;
}
}

return subjectsPassed;
}

public static void main(String[] args) {
int[] answered

--

--