HackerRank certification guide
HackerRank Python (Basic) Certification Solutions: All 10 Questions Explained
The HackerRank Python (Basic) certification gives you two coding questions, picked from a pool of ten. This page has all ten, each with Python 3 code I tested, a short summary, and a link to a full page with the reasoning, the edge cases and the mistakes that fail hidden tests.
I took this test on 8 April 2023 and passed (my certificate). My two questions were Shape Classes with Area Method and Dominant Cells. My solutions for those two are on GitHub at adminazhar/HackerRank-Python-Basic-Skills-Certification-Test-Solution.
Read the explanation, then close this page and write the code yourself. If you only copy, you will be stuck the first time HackerRank changes a detail, and you will not be able to explain the code in an interview.
What the test is
- Time: HackerRank’s test page currently says 1 hour 30 minutes. Some older write-ups say 1 hour, so check the page when you start.
- Questions: 2 coding questions, picked from the pool of 10 below. Different people get different pairs.
- Language: Pick Python 3. The stubs and every solution here are written for it.
- Format: HackerRank gives you a stub that reads the input and prints the output. You write a function or one or two classes. Hidden test cases then run your code against inputs you cannot see.
- Where: You start it from the Python (Basic) skills verification page.
The pool of ten is confirmed by many independent GitHub repos from people who took the test between 2020 and 2025. It has not changed much in that time.
How to prepare
The questions are short. You do not need algorithms or data structures beyond lists, dicts and sets. What you need is comfort with these parts of Python:
*args. A function that takes any number of arguments, likedef avg(*nums). Know thatnumsarrives as a tuple.- Classes.
__init__, storing values onself, and methods that read them back. Half the pool is “write a class with these methods”. Create lists and dicts inside__init__, not on the class. - Dunder methods.
__str__(whatprint(obj)shows),__len__(whatlen(obj)returns) and__contains__(whatx in objreturns). Two underscores on each side. - Exceptions.
raise ValueError("message")and howstr(e)gives the message back. - Strings.
split,join,swapcase,upper,lower, slicing, and the fact that'Z' < 'a'isTruebecause uppercase letters have smaller character codes. - 2D grids. Looping over rows and columns, checking all 8 neighbours of a cell, and staying inside the grid. Remember that
grid[-1]is the last row in Python, not an error.
A good way to practise: read the summary of each question below, write your own solution in a local file, and test it with a few inputs before you look at mine.
Average Function
Write avg(*nums) that returns the mean of however many integers it is given. The stub prints the result with two decimal places, so you only return sum / count. The editor gives you no signature, so you type the whole def line yourself.
def avg(*nums):
return sum(nums) / len(nums)Reverse Words Order and Swap Cases
Given a sentence of words separated by single spaces, return the words in reverse order with the case of every letter flipped. The letters inside each word keep their order, so “rUns dOg” becomes “DoG RuNS”.
def reverse_words_order_and_swap_cases(sentence):
words = sentence.split(" ")
words.reverse()
return " ".join(words).swapcase()Shape Classes with Area Method
Write a Rectangle class built from two side lengths and a Circle class built from a radius, each with an area() method. Use math.pi, not 3.14, or larger circles print the wrong area.
import math
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2Dominant Cells
Count the cells in a grid whose value is strictly greater than every neighbour, where neighbours include the diagonals. Cells on the edges and corners have fewer neighbours, and a cell equal to a neighbour does not count.
def numCells(grid):
rows = len(grid)
cols = len(grid[0])
count = 0
for r in range(rows):
for c in range(cols):
value = grid[r][c]
dominant = True
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] >= value:
dominant = False
break
if not dominant:
break
if dominant:
count += 1
return countString Representation of Objects
Write Car(max_speed, speed_unit) and Boat(max_speed) so that printing them gives a fixed sentence about their top speed. Boats are always in knots. The whole question is __str__ and getting every character of the sentence right.
class Car:
def __init__(self, max_speed, speed_unit):
self.max_speed = max_speed
self.speed_unit = speed_unit
def __str__(self):
return f"Car with the maximum speed of {self.max_speed} {self.speed_unit}"
class Boat:
def __init__(self, max_speed):
self.max_speed = max_speed
def __str__(self):
return f"Boat with the maximum speed of {self.max_speed} knots"Shopping Cart
Write an Item(name, price) class and a ShoppingCart with add(item), total() and support for len(cart). The same item can be added many times, and each add counts.
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.items = []
def add(self, item):
self.items.append(item)
def total(self):
return sum(item.price for item in self.items)
def __len__(self):
return len(self.items)String Transformation
For each word, keep the first letter and set the case of every later letter by comparing it with the letter before it in the alphabet: later in the alphabet becomes uppercase, earlier becomes lowercase, the same letter stays as it is. Compare the lowercased letters, or uppercase letters will sort before lowercase ones.
def transformSentence(sentence):
new_words = []
for word in sentence.split(" "):
if not word:
new_words.append(word)
continue
new_word = word[0]
for i in range(1, len(word)):
prev = word[i - 1].lower()
curr = word[i].lower()
if prev < curr:
new_word += word[i].upper()
elif prev > curr:
new_word += word[i].lower()
else:
new_word += word[i]
new_words.append(new_word)
return " ".join(new_words)Missing Characters
The input has only digits and lowercase letters. Return every digit and letter that does not appear, digits first, each group in order. Walking a fixed string of all 36 characters gives the right order for free.
def missingCharacters(s):
present = set(s)
result = ""
for ch in "0123456789abcdefghijklmnopqrstuvwxyz":
if ch not in present:
result += ch
return resultVending Machine
Write VendingMachine(num_items, item_price) with a buy(req_items, money) method. It returns the change on a successful sale, and raises ValueError with “Not enough items in the machine” or “Not enough coins” otherwise. Check the stock first, and only reduce it when the sale goes through.
class VendingMachine:
def __init__(self, num_items, item_price):
self.num_items = num_items
self.item_price = item_price
def buy(self, req_items, money):
if req_items > self.num_items:
raise ValueError("Not enough items in the machine")
cost = req_items * self.item_price
if money < cost:
raise ValueError("Not enough coins")
self.num_items -= req_items
return money - costMultiset Implementation
Complete a Multiset class with add, remove, the in operator and len(). It can hold the same value more than once, remove takes away one copy, and removing a value that is not there must do nothing. The template has no constructor, so add __init__ yourself.
class Multiset:
def __init__(self):
self.counts = {}
self.size = 0
def add(self, val):
self.counts[val] = self.counts.get(val, 0) + 1
self.size += 1
def remove(self, val):
if val not in self.counts:
return
self.counts[val] -= 1
if self.counts[val] == 0:
del self.counts[val]
self.size -= 1
def __contains__(self, val):
return val in self.counts
def __len__(self):
return self.sizeTips for test day
- Read the stub before you write anything. It tells you the exact function or class name, how arguments arrive and how your result is printed. Most “it works on my machine” failures are a name or return type that does not match the stub.
- Return, do not print. Unless the question says otherwise, the stub prints your return value. An extra
printinside your code adds lines the checker does not expect. - Copy exact strings from the question. Error messages and
__str__sentences are compared character by character. Watch for capitals, spaces and full stops. - Use “Run Code” with your own input. The custom input box takes the same format as the stub reads. Try the edge cases: one element, duplicates, values on the border of a grid, removing something that is not there.
- Do the easier question first. Both questions count. Get one fully passing before you spend time on the other.
- Practise before, not during. Write all ten solutions on your own machine first, so on the day you are typing something you already understand.
FAQ
How many questions are in the HackerRank Python (Basic) test?
Two coding questions. HackerRank’s test page says “Solve 2 questions”. They come from the pool of ten on this page.
How long is the test?
HackerRank’s page shows 1 hour 30 minutes as of October 2026. Some older posts say 1 hour, so trust what the test page shows when you start.
What is the pass mark?
HackerRank does not publish one. Aim to pass every test case on both questions.
Which two questions will I get?
There is no way to know. I got Shape Classes with Area Method and Dominant Cells. Public repos show many different pairs, so prepare all ten.