Skip to main content
Practice questions · Checked November 3, 2026

Codility Practice Test: 7 Sample Tasks with Solutions

This is a free Codility-style practice test: 7 original tasks where you write a solution function that hidden tests score for correctness and performance. They drill the cases that cost points, such as empty arrays, negative numbers, totals that overflow a 32-bit integer and inputs of 100,000 elements where an O(N^2) loop is too slow. Each task has examples, limits, an approach, a tested Python 3 solution and its complexity. None of them are real Codility tasks; Codility's own free demo test and lessons are the best way to learn the real editor.

How a Codility test is scored

  • A Codility test (Codility Screen) usually runs 30 minutes to 2 hours. You cannot pause it, and your code is submitted automatically when time runs out.
  • Each task is scored by hidden tests, at least 6 per task, that check correctness and performance on large inputs. The visible example does not count.
  • Code that does not compile scores 0, and how fast you finish does not change the automated score.
  • Keep the function signature exactly as given. Helper functions and standard-library imports are fine.
  • Every test gets a plagiarism check, and employers can switch on proctoring and Codility's own AI assistant for a task.

Scoring, proctoring and retakes are in our Codility guide.

The 7 Codility practice tasks

Each task gives its input limits, the way Codility tasks do. Work out the time complexity your solution needs before you write it, then list the edge cases.

#ProblemDifficultyPattern
1Longest flat stretchEasySingle pass
2Balance sign flipsEasyRunning total
3Fair split pointsMediumPrefix sums
4Close sensor pairsMediumSorting + two pointers
5Segments led by their minimumMediumMonotonic stack
6Longest run with few losing daysMediumSliding window
7Out-of-order finishersHardMerge sort counting
Problem 1EasySingle pass

Longest flat stretch

def solution(A: list[int]) -> int

A road survey records the elevation every 10 meters in array A. A flat stretch is a run of consecutive equal readings. Return the length of the longest flat stretch, or 0 if A is empty.

Examples

Input
A = [3, 3, 5, 5, 5, -2, -2]
Output
3
Input
A = [7]
Output
1
Input
A = []
Output
0

Constraints

  • N is an integer within [0..100,000].
  • Each element is an integer within [-1,000,000,000..1,000,000,000].
Show approach and solution

Approach

Walk the array once, keeping the length of the current run and the best run so far. The current run grows when a value equals the one before it and resets to 1 otherwise. Handle the empty array before the loop.

Python 3 solution
def solution(A):
    if not A:
        return 0
    best = current = 1
    for i in range(1, len(A)):
        current = current + 1 if A[i] == A[i - 1] else 1
        best = max(best, current)
    return best

Complexity: O(N) time, O(1) extra space.

What the hidden tests check: An empty array, one element, all elements equal (the answer is N), the longest run at the very end, negative values, and N = 100,000.

Problem 2EasyRunning total

Balance sign flips

def solution(A: list[int]) -> int

A wallet starts at a balance of 0, and A[i] is the change on day i. Count the days on which the balance flips sign: it becomes negative when the last nonzero balance was positive, or positive when the last nonzero balance was negative. A balance of exactly 0 has no sign and never counts as a flip.

Examples

Input
A = [5, -7, 2, 0, 3, -1]
Output
2
Why
The balances are 5, -2, 0, 0, 3, 2. Day 1 flips from positive to negative, and day 4 flips back, measured against -2, the last nonzero balance.
Input
A = [-1, 1, 1]
Output
1

Constraints

  • N is an integer within [0..100,000].
  • Each element is an integer within [-1,000,000,000..1,000,000,000], so the balance can reach 10^14.
Show approach and solution

Approach

Keep the running balance and the sign of the last nonzero balance. On each day, compute the new sign; if it is nonzero and differs from the last nonzero sign, count a flip, then remember it. The first nonzero day has nothing to flip from. In Java or C++, the balance needs a 64-bit type.

Python 3 solution
def solution(A):
    balance = 0
    last_sign = 0
    flips = 0
    for change in A:
        balance += change
        sign = (balance > 0) - (balance < 0)
        if sign != 0:
            if last_sign != 0 and sign != last_sign:
                flips += 1
            last_sign = sign
    return flips

Complexity: O(N) time, O(1) extra space.

What the hidden tests check: An empty array, balances that pass through 0 without flipping (5, then 0, then 3), the first nonzero day, and large values whose total overflows a 32-bit integer.

Problem 3MediumPrefix sums

Fair split points

def solution(A: list[int]) -> int

A split point P (0 < P < N) divides a non-empty array A into a left part A[0..P-1] and a right part A[P..N-1]. P is fair if the average of the left part is greater than or equal to the average of the right part. Return the number of fair split points.

Examples

Input
A = [4, 2, 6, 1]
Output
2
Why
P = 1 (4 vs 3) and P = 3 (4 vs 1) are fair. P = 2 compares 3 with 3.5, so it is not.
Input
A = [1, 1, 1]
Output
2
Input
A = [5]
Output
0

Constraints

  • N is an integer within [1..100,000].
  • Each element is an integer within [-1,000,000..1,000,000].
Show approach and solution

Approach

Recomputing both sums at every split point is O(N^2). Instead, take the total once and grow the left sum as P moves; the right sum is the total minus the left. Compare averages by cross-multiplying, left_sum x (N - P) >= right_sum x P, which avoids floating-point division. The products reach about 10^16, so other languages need 64-bit integers.

Python 3 solution
def solution(A):
    n = len(A)
    total = sum(A)
    left = 0
    fair = 0
    for p in range(1, n):
        left += A[p - 1]
        right = total - left
        if left * (n - p) >= right * p:
            fair += 1
    return fair

Complexity: O(N) time, O(1) extra space.

What the hidden tests check: N = 1 (no split points), all values equal (every point is fair), negative values, averages that are exactly equal, and N = 100,000 so the O(N^2) version fails the performance tests.

Problem 4MediumSorting + two pointers

Close sensor pairs

def solution(A: list[int], K: int) -> int

Sensors report readings in array A. Two readings at different indexes form a close pair if their values differ by at most K. Return the number of close pairs, that is pairs (i, j) with i < j and |A[i] - A[j]| <= K. If the number is greater than 1,000,000,000, return -1.

Examples

Input
A = [1, 5, 3, 8], K = 2
Output
2
Why
The close pairs are (1, 3) and (5, 3).
Input
A = [4, 4, 4], K = 0
Output
3

Constraints

  • N is an integer within [0..100,000].
  • Each element is an integer within [-1,000,000,000..1,000,000,000].
  • K is an integer within [0..2,000,000,000].
Show approach and solution

Approach

Order does not matter for a pair, so sort the values. Then for each right index, move a left pointer forward while the gap is more than K; every index between left and right pairs with right. The left pointer only moves forward, so the scan is O(N) after the sort. Stop and return -1 as soon as the count passes the cap.

Python 3 solution
def solution(A, K):
    values = sorted(A)
    pairs = 0
    left = 0
    for right in range(len(values)):
        while values[right] - values[left] > K:
            left += 1
        pairs += right - left
        if pairs > 1_000_000_000:
            return -1
    return pairs

Complexity: O(N log N) time for the sort, O(N) space for the sorted copy.

What the hidden tests check: An empty array, K = 0 with duplicates, extreme values (the gap between -10^9 and 10^9 does not fit in a 32-bit integer), 100,000 equal values (about 5 x 10^9 pairs, so -1), and large N where the double loop is too slow.

Problem 5MediumMonotonic stack

Segments led by their minimum

def solution(A: list[int]) -> int

Count the segments A[i..j] (i <= j) in which the first element A[i] is less than or equal to every other element of the segment. Single-element segments count. If the result is greater than 1,000,000,000, return -1.

Examples

Input
A = [2, 4, 1, 3]
Output
6
Why
Starting at 2: [2] and [2, 4]. Starting at 4: [4]. Starting at 1: [1] and [1, 3]. Starting at 3: [3].
Input
A = [3, 3, 3]
Output
6

Constraints

  • N is an integer within [1..100,000].
  • Each element is an integer within [-1,000,000,000..1,000,000,000].
Show approach and solution

Approach

A segment that starts at i stays valid until the first later element that is strictly smaller than A[i]. If that element sits at index j (or j = N if there is none), exactly j - i segments start at i. Find every j in one pass with a stack of indexes whose next smaller element is still unknown: each new value pops the indexes with larger values and becomes their answer.

Python 3 solution
def solution(A):
    n = len(A)
    next_smaller = [n] * n
    stack = []
    for j, value in enumerate(A):
        while stack and A[stack[-1]] > value:
            next_smaller[stack.pop()] = j
        stack.append(j)
    total = sum(next_smaller[i] - i for i in range(n))
    return -1 if total > 1_000_000_000 else total

Complexity: O(N) time, since each index is pushed and popped once. O(N) space.

What the hidden tests check: Equal values (they do not end a segment, because the rule is "less than or equal"), strictly decreasing arrays (the answer is N), strictly increasing arrays of 100,000 elements (about 5 x 10^9 segments, so -1), and large N where checking every segment is too slow.

Problem 6MediumSliding window

Longest run with few losing days

def solution(A: list[int], K: int) -> int

A[i] is a trader's profit on day i, negative for a loss. Return the length of the longest run of consecutive days that contains at most K losing days (days with A[i] < 0). A day with a profit of 0 is not a loss.

Examples

Input
A = [3, -1, 4, -2, -5, 6, 1], K = 2
Output
5
Why
[4, -2, -5, 6, 1] has exactly 2 losing days.
Input
A = [-3, -1], K = 0
Output
0

Constraints

  • N is an integer within [0..100,000].
  • K is an integer within [0..N].
  • Each element is an integer within [-1,000,000,000..1,000,000,000].
Show approach and solution

Approach

Grow a window to the right and count the losing days inside it. When the count goes past K, move the left edge forward until it is back to K, dropping a loss whenever a losing day leaves the window. Record the longest window. Trying every start day would be O(N^2).

Python 3 solution
def solution(A, K):
    best = 0
    losses = 0
    left = 0
    for right, profit in enumerate(A):
        if profit < 0:
            losses += 1
        while losses > K:
            if A[left] < 0:
                losses -= 1
            left += 1
        best = max(best, right - left + 1)
    return best

Complexity: O(N) time, since each index enters and leaves the window once. O(1) extra space.

What the hidden tests check: K = 0 with every day a loss (the answer is 0), K at least the number of losing days (the answer is N), days with 0 profit, an empty array, and large N.

Problem 7HardMerge sort counting

Out-of-order finishers

def solution(A: list[int]) -> int

A[i] is the finishing time of the runner who wore bib number i. A pair of runners (i, j) with i < j is out of order if the runner with the lower bib finished later, that is A[i] > A[j]. Equal times are not out of order. Return the number of out-of-order pairs, or -1 if it is greater than 1,000,000,000.

Examples

Input
A = [3, 1, 2, 5, 4]
Output
3
Why
The pairs are (3, 1), (3, 2) and (5, 4).
Input
A = [2, 2, 1]
Output
2

Constraints

  • N is an integer within [0..100,000].
  • Each element is an integer within [-1,000,000,000..1,000,000,000].
Show approach and solution

Approach

Checking every pair is O(N^2). Merge sort counts them while it sorts: when merging two sorted halves, each time an element from the right half is placed before the remaining elements of the left half, it is out of order with all of them. Take from the left half on ties (<=), so equal times are not counted.

Python 3 solution
def solution(A):
    def sort_count(values):
        if len(values) <= 1:
            return values, 0
        mid = len(values) // 2
        left, a = sort_count(values[:mid])
        right, b = sort_count(values[mid:])
        merged = []
        count = a + b
        i = j = 0
        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                count += len(left) - i
                j += 1
        merged.extend(left[i:])
        merged.extend(right[j:])
        return merged, count

    _, total = sort_count(A)
    return -1 if total > 1_000_000_000 else total

Complexity: O(N log N) time, O(N) space.

What the hidden tests check: Sorted input (0), reverse-sorted input of 100,000 elements (about 5 x 10^9 pairs, so -1), duplicates, empty and single-element arrays, and large N where the O(N^2) loop fails the performance tests.

How to practice for the Codility round

  1. Step 1

    Take Codility's free demo test

    The 30-minute demo task uses the real editor and scoring, so you see how hidden tests and auto-submit work before the real test.

  2. Step 2

    Set a target complexity first

    Read the input limits and decide the complexity you need before you code. With N up to 100,000, O(N^2) is about 10^10 steps, far too slow; O(N log N) or O(N) is the target.

  3. Step 3

    Write your own edge-case tests

    Codility lets you add test cases. For every task, try empty input, one element, all equal values, negatives, the largest values and the largest N.

  4. Step 4

    Keep a version that compiles

    Code that does not compile scores 0, and time running out submits whatever is in the editor. Get a correct simple version in place, then improve it.

  5. Step 5

    Work through the free lessons

    Codility's 17 free lessons run from arrays and time complexity through prefix sums, stacks, sorting and the caterpillar method to dynamic programming, each with practice tasks.

OphyAI Desktop for Mac and Windows

Practice with these, then use Coding Copilot in your Codility 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 Codility 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 task, 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 its complexity with yours.

In a live Codility 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

Every test gets a plagiarism check, and employers can add paste and tab tracking, webcam snapshots, screen recording and a desktop app that looks for hidden tools. Employers can also turn on Codility's own assistant, Claude Code or Codex for a task, with every prompt saved.

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.

Codility practice test FAQ

Codility's free 30-minute demo test uses the real editor and scoring, and its 17 free lessons cover topics from arrays and prefix sums to dynamic programming. The 7 original tasks here add correctness and performance edge cases to drill.

Yes. Codility's free demo test is one task in 30 minutes, scored the same way as a real test. This page is a longer practice set of 7 tasks in the same style.

The example test does not count. Hidden tests, at least 6 per task, check edge cases and speed on large inputs, so a correct but slow solution loses the performance tests.

Read the input limits in the task and estimate. With N up to 100,000, an O(N^2) solution means about 10^10 steps, far too slow, while O(N log N) is about 2 million and passes easily.

Any language the employer allows; Codility's demo test lists 21, including Python, Java, C++, JavaScript and Go. In Java or C++, watch for overflow: a sum of 100,000 values near 1,000,000,000 does not fit in a 32-bit int.

No. They are original practice tasks in Codility's style. Codility compares every submission with more than 12 million past answers and with AI-written answers, so practicing patterns beats memorizing answers.

Yes. Coding Copilot in the OphyAI desktop app reads a task on your screen with one hotkey and returns code with a dry run, edge cases and the Big O, so you can check your attempts. It also works on the Codility test itself and in live Codility interviews, in an overlay that screen sharing and recording leave out. It does not hide from a webcam or from Codility's own paste and tab tracking.

Practice here, then take Coding Copilot into your Codility 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.