Introduction to HackerRank for Python Programmers

HackerRank is a site where you can supercharge your Python programming skills, master data structures and algorithms, and stand out to prospective employers by solving challenges alongside programmers from all around the world. It is also used by recruiters to evaluate prospective employees’ abilities.

If you are learning Python, which is the main focus of this blog, you will find a huge amount of material to help you develop your skills. However Python is by no means the only language available. For example you can use HackerRank to practice

  • C, C++, Java, C#, Python, PHP, Ruby, Go, and Swift
  • databases/SQL
  • machine learning
  • regex
  • rest APIs

and more.

There is a something of a Marmite thing going on around whether people love or hate HackerRank. (If you don’t live in the UK you might not get that reference – Marmite is a salty yeast extract which some people find delicious but which turns others’ stomachs.)

Here’s some of the reason people love or hate HackerRank:

Reasons people love HackerRank

  • It gives objective feedback about your skill level at solving a particular types of problem
  • It gives an opportunity to develop your skill in several areas of programming
  • Community and discussion of different approaches and insights into the problems
  • Structured learning with progressively harder challenges
  • Develop you problem solving skills
  • Sets of challenges are available for focusing specific skills

Reasons people hate HackerRank

  • The challenges can be hard to solve
  • The descriptions are sometimes unclear or overcomplicated
  • The types of challenges may well not reflect the kinds tasks you will be doing in a development job
  • The UI can be confusing
  • Best practices are often not used e.g. naming of function arguments

The rest of this article is for people who want to give HackerRank a try. In it I will help to demystify the site and help you to get started with solving the challenges.

How to Solve a Python HackerRank Challenge

Let’s take a look at a challenge from the Interview Preparation Kit Warm-up Challenges: Repeated String. A big part of solving theses challenges is being able to decipher what you are supposed to do based on the problem description. This is by no means always easy, and you will probably need to complete a few challenges to get to the point where the problem descriptions don’t make your brain hurt. Here’s a screen grab of the Repeated String Challenge. Don’t be disheartened if it looks confusing – I will explain it next.

HackerRank for Python Programmers Repeated String Description

HackerRank for Python Programmers - Repeated String

OK, that might look like gobbledegook, so allow me to simplify things for you. The idea is that, given a string, like abc, you need to work out how many times the letter a would appear in the string if it were repeated until it were of the given length.

Confused?

Say you have the string abc, and the length given is 10. The full string would become abcabcabca, (repeating abc until we have 10 characters), and the number of as in the resulting string is 4.

One thing to note is that the initial template provide by HackerRank may contain some very confusing code along with the blank function definition. What you should understand is that this code is needed by the platform to test your code. You don’t actually need to understand how it works, but instead should simply focus on competing the function definition. By which I mean, ignore this bit:

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    n = int(input())

    result = repeatedString(s, n)

    fptr.write(str(result) + '\n')

    fptr.close()

How Tests Work in HackerRank Challenges

A fundamental concept you need to understand when attempting HackerRank challenges is tests. When you submit your code it will be run with number of different inputs and the results compared with expected (correct) results. You code will need to pass all the test in order for you to successfully complete the challenge.

Sometimes your code will pass some of the tests but not all of them. You then have the option of “purchasing” access to the failed tests using “Hakos” – these are virtual credits earned by solving challenges.

You can run the code with your own input using the form shown below.

HackerRank Python Input Values

One useful tip is when you think you have a working solution, to paste in the sample input given in the problem description to see if your solution gives the expected result. This will give you an initial indication of whether your code is “in the right ball park”.

You may get a error message, which is helpful in debugging you code, and you can also use print statements to see the values of variables during your code’s execution, and the output will be displayed when you run it…

Initial Attempt at HackerRank Repeated String challenge – Memory Issue

Spoiler alert: Try the problem for yourself before reading on to get the most learning from this article.

If you are very new to programming, you might need to spend a bit of time elsewhere getting past beginner level. One thing that makes the challenges on HackerRank well, challenging, is that it is often not enough to simply write a correct solution. In addition there may well be constraints in terms of speed of execution and memory requirements. This is where your knowledge of algorithmic efficiency comes in, or if you don’t have that knowledge, where you get the opportunity to dive into that fascinating topic.

Here is my initial attempt at solving the HackerRank Repeated String challenge.

def repeatedString(s, n):
    long_string = s * (n // len(s))
    num_extra_chars = n - len(long_string)
    long_string += s[:num_extra_chars]
    return long_string.count("a")

Note: s[:num_extra_chars] means “slice the string from the beginning to the position of num_extra_chars.

Can you see what my thinking was? I created the full version of the repeated string in hopes of then counting the number of as. Unfortunately, some of the tests involved a very large value for n which meant that there was insufficient memory available. I had to rethink my approach.

Repeated String Warm-up Challenge

Here is my working solution to the Repeated String Warm-up HackerRank Challenge in Python

def repeatedString(s, n):    
    repeating_section_length = len(s)
    full_repetitions = n // repeating_section_length
    partial_result = s.count("a") * full_repetitions
    num_extra_chars = s[: n % repeating_section_length].count("a")
    return partial_result + num_extra_chars

The key here was to avoid actually creating the full string of length n, but instead to use powerful modulo operator (%) to perform the calculation instead.


In this article we have explored what HackerRank is and how to approach the programming challenges available there. I hope you have found it helpful. Please feel free to comment below and share your experience with HackerRank.

Happy computing!

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Join our mailing list

Join our mailing list to receive awesome articles about learning Python and Computer Science in a fun and accessible way, straight to your inbox.