Overview
In your HackerRank Coding questions, your test setter may have already defined a method or function which you must complete with a logical answer to return the expected output.
Example: A coding question may require you to complete the logic in a given function defined as:
int Sum(int num1, int num2)
This article suggests how to debug your logic in a function using Debug print statements and Custom input values.
Note: If a coding question requires you to write a complete program to identify the solution, refer to the Debugging a complete program topic.
Using debug statements to test the logic
Test the logic in your function by including debug print statements and print the output to STDOUT. For instance, include print statements such as printf() or Console.WriteLine() to test the output returned at different logical areas of your code.
Example: Consider a coding question that requires you to complete the given function:
int Sum(int num1, int num2) to calculate the sum of integers.
Assuming that your logic is not returning the expected output, include debug print statements at different logical blocks of the function, and click Run code.
The debug output values are captured separately and printed in the Debug Output area, as shown below:
Note: The input and output values are displayed only for Sample Test Cases.
Using Custom Input Values to test the logic in functions
Click the “Test against custom input” option to debug and test your function using your own input values. You can use this option along with debugging statements included in your code.
Note: The Test against custom input option is available only if it is permitted in your test.
Use the Visual format to easily add custom input values to the function, and click Run code. A custom test case executes your logic using the given input values. The debug outputs and the actual output returned by the function are captured and printed separately as shown below:
In some cases, to help you to understand the expected output for the problem, your test setter may have included a hidden solution in the question. In this scenario, the Expected Output area displays the correct output from the hidden solution for the given custom input values.
Example: The hidden solution executes and displays the expected output as shown below:
Note: When you finish debugging, ensure that you uncheck the "Test against custom input" option and remove all the debug statements from the code. Before submitting the answer, it is recommended that you re-run your logic and validate all the test cases for successful execution.
For a detailed understanding of coding question test cases, refer to the following topics: