HackerRank Practice Questions: 8 Test Examples with Solutions
These are 8 original practice questions written like HackerRank coding tests: you complete a function, and hidden test cases decide the score, so partial credit and edge cases matter. They cover the topics HackerRank says companies test most, such as arrays, hash maps, sorting and strings, plus stacks, binary search, graphs, dynamic programming and shortest paths. Each one has examples, constraints, an approach, a tested Python 3 solution and a list of what the hidden tests check. None of them are real HackerRank test questions.
There is no standard HackerRank test. The company picks the questions, the time limit and the languages, and your login page shows them.
Coding questions ask you to complete a function that is checked against test cases. Some are visible, others are hidden, and each can carry its own points.
Your score is the sum of the test cases you pass, so partial credit is normal. Running your code does not change your score.
Copy and paste tracking, tab tracking and a code-similarity check are on by default. Companies can also turn on HackerRank's own AI assistant for a test.
Each question gives a function to complete. Pass the examples first, then think about what the hidden tests will throw at it before you open the solution.
def countLateCheckins(times: list[str], cutoff: str) -> int
A clinic records patient check-in times as 24-hour strings like "08:45". Given the list times and a cutoff time in the same format, return how many check-ins happened strictly after the cutoff.
Examples
Input
times = ["08:59", "09:00", "09:01", "13:30"]
cutoff = "09:00"
Output
2
Why
"09:00" is on time, not late. Only "09:01" and "13:30" are after the cutoff.
Input
times = ["00:00", "23:59"]
cutoff = "23:59"
Output
0
Constraints
0 <= len(times) <= 100,000
Every time is a valid zero-padded "HH:MM" string.
Show approach and solution
Approach
Convert each time to minutes after midnight and compare numbers. Comparing the strings directly also works for zero-padded times, but converting is safer if the format ever changes and is easier to explain.
Python 3 solution
def to_minutes(clock):
hours, minutes = clock.split(':')
return int(hours) * 60 + int(minutes)
def countLateCheckins(times, cutoff):
limit = to_minutes(cutoff)
return sum(1 for t in times if to_minutes(t) > limit)
Complexity: O(n) time, O(1) extra space.
What the hidden tests check: An empty list, times equal to the cutoff (not late), "00:00", a cutoff of "23:59", and 100,000 times.
Problem 2EasyHash map counting
Most common word
def mostCommonWord(text: str) -> str
Return the word that appears most often in text. Words are runs of the letters a-z, case does not matter, and every other character separates words. Return the word in lowercase. If words tie, return the one that comes first alphabetically. If there are no words, return an empty string.
Examples
Input
text = "The cat and the hat. THE END"
Output
"the"
Input
text = "b a, b a"
Output
"a"
Why
a and b both appear twice, and a comes first.
Input
text = "123 !!!"
Output
""
Constraints
0 <= len(text) <= 100,000
text is ASCII.
Show approach and solution
Approach
Lowercase the text, pull out the letter runs, and count them in a hash map. To pick the winner, take the minimum by the key (negative count, word): the highest count wins, and the alphabetical word breaks ties.
Python 3 solution
import re
from collections import Counter
def mostCommonWord(text):
counts = Counter(re.findall('[a-z]+', text.lower()))
if not counts:
return ''
return min(counts, key=lambda word: (-counts[word], word))
Complexity: O(n) time, O(w) space for w distinct words.
What the hidden tests check: Empty text, text with only digits or punctuation, ties between several words, mixed case, and apostrophes that split a word in two.
Problem 3MediumStack
Bracket depth
def bracketDepth(s: str) -> int
A string may contain the brackets (), [] and {} mixed with other characters. Return the maximum nesting depth of the brackets. If the brackets are not balanced or not properly nested, return -1. A string with no brackets has depth 0.
Examples
Input
s = "a(b[c]{d})"
Output
2
Input
s = "([)]"
Output
-1
Why
The pairs cross, so they are not properly nested.
Input
s = "(("
Output
-1
Input
s = "no brackets"
Output
0
Constraints
0 <= len(s) <= 100,000
Show approach and solution
Approach
Push each opening bracket on a stack and track the largest stack size. On a closing bracket, the top of the stack must be its matching opener; if the stack is empty or the top does not match, return -1. At the end, a non-empty stack means unclosed brackets.
Python 3 solution
def bracketDepth(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
deepest = 0
for ch in s:
if ch in '([{':
stack.append(ch)
deepest = max(deepest, len(stack))
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return -1
return deepest if not stack else -1
Complexity: O(n) time, O(n) space in the worst case.
What the hidden tests check: Unclosed openers at the end, a closer with an empty stack, crossed pairs like "([)]", nesting 100,000 deep (a recursive solution can hit Python's recursion limit), and strings with no brackets.
Problem 4MediumSorting + two pointers
Loading docks
def minDocks(arrivals: list[int], departures: list[int]) -> int
Trucks visit a warehouse during the day. Truck i arrives at arrivals[i] and leaves at departures[i], in minutes after opening, with arrival before departure. Each truck needs its own dock while it is there, and a dock freed at minute t can take a truck that arrives at minute t. Return the minimum number of docks so that no truck waits.
At minute 25, the trucks that arrived at 0, 20 and 25 are all at the docks.
Input
arrivals = [5, 10]
departures = [10, 20]
Output
1
Why
The first truck leaves at minute 10, just as the second arrives, so they share one dock.
Constraints
0 <= n <= 100,000
0 <= arrivals[i] < departures[i] <= 10^9
The input is not sorted.
Show approach and solution
Approach
Sort arrivals and departures separately. Walk the arrivals in order; before placing each truck, release every dock whose departure is at or before this arrival. The most docks in use at any moment is the answer. Releasing on "at or before" is what lets a dock be reused at the same minute.
Python 3 solution
def minDocks(arrivals, departures):
starts = sorted(arrivals)
ends = sorted(departures)
in_use = 0
most = 0
j = 0
for start in starts:
while j < len(ends) and ends[j] <= start:
in_use -= 1
j += 1
in_use += 1
most = max(most, in_use)
return most
Complexity: O(n log n) time for the sorts, O(n) space.
What the hidden tests check: No trucks, a departure and an arrival at the same minute, every truck overlapping, unsorted input, and 100,000 trucks so the O(n^2) pairwise check is too slow.
errors[i] is the number of errors a service logged in minute i, starting at minute 0. For each threshold in queries, return the first minute by which the running total of errors has reached at least that threshold, or -1 if it never does.
Because errors are never negative, the running totals never go down, so they are sorted. Build them once, then answer each query with a binary search for the first total that is at least the threshold. Scanning the totals for every query would be O(n x q), too slow at 100,000 each.
Python 3 solution
from bisect import bisect_left
from itertools import accumulate
def firstMinuteReached(errors, queries):
totals = list(accumulate(errors))
answers = []
for threshold in queries:
minute = bisect_left(totals, threshold)
answers.append(minute if minute < len(totals) else -1)
return answers
Complexity: O(n + q log n) time, O(n) space.
What the hidden tests check: Minutes with zero errors (the answer is the first minute that reaches the threshold, not a later one with the same total), thresholds above the grand total, thresholds reached exactly, and 100,000 queries.
Problem 6MediumBreadth-first search
Warehouse robot route
def shortestPath(grid: list[str]) -> int
A warehouse floor is a grid of strings. 'S' is the robot's start, 'E' is the packing station, '#' is a shelf the robot cannot enter, and '.' is open floor. The robot moves one cell up, down, left or right per step. Return the fewest steps from S to E, or -1 if E cannot be reached.
Examples
Input
grid = ["S.#",
"..#",
"#.E"]
Output
4
Input
grid = ["S#E"]
Output
-1
Constraints
1 <= rows, cols <= 500
There is exactly one S and one E.
Show approach and solution
Approach
Breadth-first search from S explores cells in order of distance, so the first time it reaches E is the shortest path. Mark cells as seen when you add them to the queue, not when you pop them, so no cell is queued twice.
Python 3 solution
from collections import deque
def shortestPath(grid):
rows, cols = len(grid), len(grid[0])
start = next((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 'S')
queue = deque([(start[0], start[1], 0)])
seen = {start}
while queue:
r, c, steps = queue.popleft()
if grid[r][c] == 'E':
return steps
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] != '#' and (nr, nc) not in seen:
seen.add((nr, nc))
queue.append((nr, nc, steps + 1))
return -1
Complexity: O(rows x cols) time and space.
What the hidden tests check: E walled off, S right next to E, a single-row grid, long winding corridors, and a 500 x 500 open grid where a search without a visited set never finishes.
Problem 7MediumDynamic programming
Training plan points
def maxTrainingPoints(cardio: list[int], weights: list[int]) -> int
You are planning n days of training. On day i you can do cardio for cardio[i] points, lift weights for weights[i] points, or rest for 0 points. You may not lift weights on two days in a row. Return the most points you can earn.
Examples
Input
cardio = [3, 2, 5]
weights = [10, 10, 1]
Output
18
Why
Cardio, weights, cardio earns 3 + 10 + 5. Lifting on days 1 and 2 is not allowed.
Input
cardio = [1, 1, 1]
weights = [5, 5, 5]
Output
11
Constraints
1 <= n <= 100,000
0 <= cardio[i], weights[i] <= 10,000
Show approach and solution
Approach
Track two best totals as you go: the best plan whose last day was not a lifting day, and the best plan whose last day was. A lifting day can only follow a non-lifting day; a non-lifting day (cardio or rest) can follow either. Trying every plan would be 3^n.
Python 3 solution
def maxTrainingPoints(cardio, weights):
no_lift = 0
lift = float('-inf')
for c, w in zip(cardio, weights):
no_lift, lift = max(no_lift, lift) + max(c, 0), no_lift + w
return max(no_lift, lift)
Complexity: O(n) time, O(1) extra space.
What the hidden tests check: A single day, weights always worth more than cardio (the best plan alternates), all zeros, and 100,000 days.
Problem 8HardDijkstra on (node, state)
Toll roads with one free pass
def cheapestTrip(n: int, roads: list[list[int]]) -> int
A delivery van drives on a network of n towns numbered 0 to n - 1. roads[i] = [a, b, toll] is a two-way road between towns a and b that costs toll dollars. The driver has one free pass that makes a single road cost 0. Return the cheapest total cost from town 0 to town n - 1, or -1 if it cannot be reached.
Take 0 to 1 for 5, then use the pass on the 20-dollar road to 3.
Input
n = 3
roads = [[0, 1, 4]]
Output
-1
Constraints
1 <= n <= 10,000
0 <= len(roads) <= 50,000 and 0 <= toll <= 10,000
Two towns can be joined by more than one road.
Show approach and solution
Approach
Run Dijkstra on states (town, pass used or not). From each state, a road can be paid as usual, or, if the pass is unused, taken for 0 and the pass marked used. The first time any state for town n - 1 comes off the heap, its cost is the cheapest. Running a separate Dijkstra for every choice of free road would be far too slow.
Python 3 solution
import heapq
def cheapestTrip(n, roads):
graph = [[] for _ in range(n)]
for a, b, toll in roads:
graph[a].append((b, toll))
graph[b].append((a, toll))
best = [[float('inf')] * 2 for _ in range(n)]
best[0][0] = 0
heap = [(0, 0, 0)]
while heap:
cost, town, used = heapq.heappop(heap)
if cost > best[town][used]:
continue
if town == n - 1:
return cost
for nxt, toll in graph[town]:
if cost + toll < best[nxt][used]:
best[nxt][used] = cost + toll
heapq.heappush(heap, (cost + toll, nxt, used))
if not used and cost < best[nxt][1]:
best[nxt][1] = cost
heapq.heappush(heap, (cost, nxt, 1))
return -1
Complexity: O((n + m) log(n + m)) time for m roads, O(n + m) space.
What the hidden tests check: No route at all, start equal to the destination (n = 1, answer 0), parallel roads with different tolls, routes where the pass is best spent on an early road, and large networks.
How to practice for the HackerRank round
Step 1
Take the official sample test first
HackerRank's free sample test, and the Try Sample Test button on your login page, show the editor, the Run button and how test cases appear, so nothing is new on the day.
Step 2
Code against the hidden tests in your head
Before you run anything, list the edge cases for the question: empty input, one element, duplicates, the largest size. Then check them yourself, because the hidden tests will.
Step 3
Time yourself in mixed sets
Do two or three of these questions back to back with a timer. Aim to pass the examples fast, then spend the rest of the time on edge cases and speed.
Step 4
Drill the topics, then mix
Work through HackerRank's Interview Preparation Kit by topic, starting with arrays, hash maps, sorting and strings, then come back to mixed sets like this one.
OphyAI Desktop for Mac and Windows
Practice with these, then use Coding Copilot in your HackerRank interview
Coding Copilot in the OphyAI desktop app reads the coding problem on your screen with one hotkey and returns an approach, complexity notes and working code in your language.
Practice with these, then bring Coding Copilot into the real HackerRank interview. While you practice, press Cmd/Ctrl + Shift + A to snap the problem window, or Cmd/Ctrl + Shift + S to drag a box around one question, and Coding Copilot returns an answer card: how it read the problem, what to say first, the code with line numbers, a dry run with edge cases, and the Big O. Compare it with your own attempt.
In a live HackerRank Interview, press Space or Cmd/Ctrl + Shift + L and it transcribes the question your interviewer asks out loud. The card shows in a floating overlay that macOS and Windows leave out of screen sharing and recording. It stays on top of a full-screen editor or browser and opens without taking focus from your editor.
Cmd/Ctrl + Shift + A snaps the problem window, even when other windows cover it, and Cmd/Ctrl + Shift + S lets you drag a box around part of the screen. In a live interview, Space or Cmd/Ctrl + Shift + L transcribes the question the interviewer asks out loud.
Answers show as a card in a floating overlay that macOS and Windows leave out of screen sharing and recording. It stays on top of a full-screen editor or browser and opens without taking the keyboard from your editor.
Each answer card shows how OphyAI read the problem, what to say first, the code with line numbers, a dry run with edge cases, and the Big O. Follow-ups remember the problem, so "now handle duplicates" updates the same code.
Free download. Coding Interview is on the Premium plan ($59 a month, 500 credits) and uses 15 credits per session. See everything it does
What it is hidden from, and what it is not
Copy and paste tracking, tab tracking and a code-similarity check run by default, and companies can add webcam photos, full-screen Secure Mode, screen recording, or a desktop app that blocks AI apps. Companies can also turn on HackerRank's own AI assistant, and the evaluator sees your chats with it.
The OphyAI window is hidden from screen sharing and recording, but not from a webcam, a person watching, or the platform's own keystroke, paste and tab tracking.
HackerRank practice questions FAQ
HackerRank's free sample test, also the Try Sample Test button on your login page, shows the real editor and how test cases appear. The Interview Preparation Kit groups practice problems by topic. The 8 original questions here use the same complete-the-function style.
It depends on the company. HackerRank lists 18 question types for candidates, including coding, SQL, multiple choice and project tasks. In its Interview Preparation Kit, arrays, hash maps, sorting and string manipulation are the topics HackerRank says the most companies test.
No. Every question here is original, written for practice. Real tests use the questions the company picked, and HackerRank's MOSS check compares your code with other candidates' submissions, so memorized answers are a bad plan anyway.
You do not see their input or expected output, and each one can carry its own points. Your score is the sum of the cases you pass, so empty input, very large input and duplicates are where points are won or lost.
Any language the company allows; HackerRank supports more than 60. Pick the one you are fastest in. In Java, C# or Scala the main class must be named Solution; Python skips that boilerplate, which is why the solutions here use it.
No. Running your code does not affect your score, so run it as often as you like. Submit every question before time runs out.
Yes. Coding Copilot in the OphyAI desktop app reads a problem on your screen with Cmd/Ctrl + Shift + A and returns an approach and working code to check your attempts against. It also works on the HackerRank test itself and in live HackerRank interviews, in an overlay that screen sharing and recording leave out. It does not hide from a webcam or from HackerRank's own tracking.
Sources
Format facts read on November 3, 2026. Every problem on this page is original and written by OphyAI for practice; none is a real HackerRank question. OphyAI is not affiliated with HackerRank.
Practice here, then take Coding Copilot into your HackerRank interview
Download OphyAI Desktop and bring Coding Copilot into your next coding interview: it hears the question, reads the problem, and shows the approach and code in an overlay your screen share leaves out.