Autocoder

Thoughtworks Coding Round Questions

Last updated 2026-11-19

The coding round most associated with Thoughtworks is a pairing or take-home exercise on a small, realistic problem: a Mars Rover, a bowling scorer, a tic-tac-toe board. The marks go to readable code, sensible tests and clear communication more than to cleverness. This page works through eleven kata-style problems in Python and Java, with the solution, complexity and the mistakes that are easy to make under observation.

They are practice problems in the style of those exercises, not copies of any task. Read how to crack the pair programming interview for the live-session habits, and Thoughtworks interview questions for the design and culture side.

StyleSmall katas, pair programming, test-first
Languages herePython and Java
Judged onReadability, tests, design, communication

How to approach a kata

Write the first test from the examples in the statement, make it pass in the simplest way, then add the next case. Model the domain with small objects or pure functions, give things names from the problem, and keep each function short enough to describe in one sentence. Say aloud which edge cases you are choosing not to handle yet.

Complexity still matters but is rarely the point: state it briefly and move on to design.

Hiring status

We hold no sourced details of Thoughtworks assessments beyond the third-party stage description on the interview page, and no openings or dates. Check thoughtworks.com/careers for current information.

Thoughtworks Coding Round Questions: questions with worked answers

  1. 1

    Mars Rover: a rover has a position and a heading. Commands are L, R (turn 90 degrees) and M (move one step). Return its final position.

    easy

    Model the rover as a small class with the heading as an index into the list N, E, S, W so that turning is index arithmetic modulo 4. A move changes x or y by the heading's delta. Each command is O(1), so the whole run is O(commands). Mistakes: encoding headings as strings with a chain of ifs, handling invalid commands silently, and mixing parsing with movement. Add a test for each command before the sequence test.

    python
    class Rover:
        HEADINGS = "NESW"
        DELTA = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
    
        def __init__(self, x, y, heading):
            self.x, self.y, self.i = x, y, self.HEADINGS.index(heading)
    
        def run(self, commands):
            for cmd in commands:
                if cmd == "L":
                    self.i = (self.i - 1) % 4
                elif cmd == "R":
                    self.i = (self.i + 1) % 4
                elif cmd == "M":
                    dx, dy = self.DELTA[self.HEADINGS[self.i]]
                    self.x, self.y = self.x + dx, self.y + dy
                else:
                    raise ValueError("bad command " + cmd)
            return self.x, self.y, self.HEADINGS[self.i]
    
    print(Rover(1, 2, "N").run("LMLMLMLMM"))  # (1, 3, 'N')
  2. 2

    Roman numerals: convert an integer from 1 to 3999 to a Roman numeral.

    easy

    Walk a table of value and symbol pairs in descending order, including the subtractive pairs (900, 400, 90, 40, 9, 4), and append while the number is at least the value. O(1) since the table and the maximum output length are bounded. Mistake: forgetting the subtractive pairs and producing "IIII" for 4. Write the test for 4, 9, 40, 90, 400, 900 and 1994 first.

    python
    PAIRS = [(1000,"M"),(900,"CM"),(500,"D"),(400,"CD"),(100,"C"),(90,"XC"),
             (50,"L"),(40,"XL"),(10,"X"),(9,"IX"),(5,"V"),(4,"IV"),(1,"I")]
    
    def to_roman(n):
        out = []
        for value, sym in PAIRS:
            while n >= value:
                out.append(sym)
                n -= value
        return "".join(out)
    
    print(to_roman(1994))  # MCMXCIV
  3. 3

    String calculator: add("1,2\n3") returns 6; a custom delimiter is declared as "//;\n1;2"; negatives throw an exception listing them.

    easy

    Build it test-first in steps: empty string returns 0, one number, two numbers, newline as delimiter, custom delimiter, then negatives. Parse with a regular expression split on the chosen delimiter. O(length). Mistake: writing the whole parser at once rather than step by step, and not escaping the delimiter when it is a regex special character such as the full stop or a pipe; use re.escape.

    python
    import re
    
    def add(s):
        if not s:
            return 0
        delim = r",|\n"
        if s.startswith("//"):
            header, s = s.split("\n", 1)
            delim = re.escape(header[2:])
        nums = [int(x) for x in re.split(delim, s)]
        neg = [n for n in nums if n < 0]
        if neg:
            raise ValueError("negatives not allowed: " + ", ".join(map(str, neg)))
        return sum(nums)
    
    print(add("1,2\n3"), add("//;\n1;2"))  # 6 3
  4. 4

    Bowling game: given the list of rolls for a complete game, compute the score.

    medium

    Walk ten frames with an index. A strike (10) scores 10 plus the next two rolls and advances by one; a spare scores 10 plus the next roll and advances by two; an open frame scores its two rolls. The tenth-frame bonus rolls are read as lookahead, so no special case is needed. O(n). Mistake: adding bonus balls as extra frames, or advancing by two after a strike. Test a perfect game (twelve strikes is 300) and a game of all spares with a final 5 (150).

    python
    def bowling(rolls):
        score = i = 0
        for _ in range(10):
            if rolls[i] == 10:
                score += 10 + rolls[i + 1] + rolls[i + 2]
                i += 1
            elif rolls[i] + rolls[i + 1] == 10:
                score += 10 + rolls[i + 2]
                i += 2
            else:
                score += rolls[i] + rolls[i + 1]
                i += 2
        return score
    
    print(bowling([10] * 12), bowling([5] * 21))  # 300 150
  5. 5

    Conway's Game of Life: given the set of live cells, compute the next generation.

    medium

    Count live neighbours for every cell adjacent to a live one using a Counter, then apply the rules: a cell is alive next turn if it has exactly 3 neighbours, or 2 and is already alive. This sparse representation handles an unbounded grid. O(live cells) per generation. Mistake: using a fixed array and falling off the edges, or updating the grid in place so later cells see already-updated neighbours.

    python
    from collections import Counter
    
    def step(live):
        counts = Counter(
            (x + dx, y + dy)
            for x, y in live
            for dx in (-1, 0, 1)
            for dy in (-1, 0, 1)
            if (dx, dy) != (0, 0)
        )
        return {cell for cell, n in counts.items() if n == 3 or (n == 2 and cell in live)}
    
    blinker = {(0, 1), (1, 1), (2, 1)}
    print(sorted(step(blinker)))  # [(1, 0), (1, 1), (1, 2)]
  6. 6

    Tic-tac-toe: given a 3x3 board, report the winner, a draw or "in progress".

    medium

    List the eight winning lines as coordinate triples and check whether any is filled with one non-empty mark. If none and no empty cell remains, it is a draw. Constant time for a fixed size; for an NxN board generalise with row, column and diagonal counters. Mistake: checking only rows, and treating the board as invalid when both players seem to win, which the statement may require you to detect.

    java
    public class TicTacToe {
        private static final int[][] LINES = {
            {0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}};
    
        public static String result(char[] b) {
            for (int[] l : LINES) {
                if (b[l[0]] != ' ' && b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]]) {
                    return String.valueOf(b[l[0]]) + " wins";
                }
            }
            for (char ch : b) if (ch == ' ') return "in progress";
            return "draw";
        }
    }
  7. 7

    Word wrap: break a text into lines of at most N characters without splitting words.

    medium

    Greedily add words to the current line while the line plus a space plus the word fits; otherwise start a new line. A word longer than N gets its own line, or is split if the statement says so. O(length of text). Mistake: producing a trailing space, or an off-by-one when counting the separating space. Test with a word exactly N long and with an empty string.

    python
    def wrap(text, n):
        lines, cur = [], ""
        for word in text.split():
            if not cur:
                cur = word
            elif len(cur) + 1 + len(word) <= n:
                cur += " " + word
            else:
                lines.append(cur)
                cur = word
        if cur:
            lines.append(cur)
        return lines
    
    print(wrap("the quick brown fox jumps", 10))  # ['the quick', 'brown fox', 'jumps']
  8. 8

    Prime factors: return the prime factors of n in ascending order.

    medium

    Trial division: divide by candidate d starting from 2 while d * d <= n; whenever d divides n, record it and divide it out; whatever is left above 1 is a prime. O(sqrt n). Mistake: looping d up to n, which is far slower, and forgetting the remaining prime factor after the loop (for example 14 leaves 7).

    java
    import java.util.*;
    
    public class Factors {
        public static List<Long> of(long n) {
            List<Long> out = new ArrayList<>();
            for (long d = 2; d * d <= n; d++) {
                while (n % d == 0) { out.add(d); n /= d; }
            }
            if (n > 1) out.add(n);
            return out;
        }
    }
  9. 9

    Bank account kata: deposit, withdraw and print a statement with date, amount and running balance, newest first.

    medium

    Keep an immutable list of transactions and compute the running balance when printing, rather than storing it per row. Inject a clock so dates are testable, and reject non-positive amounts and overdrafts with clear exceptions. O(transactions) to print. Mistake: calling the system time inside the account class, which makes tests non-deterministic, and storing money as floating point; use integer paise or Decimal.

    python
    class Account:
        def __init__(self, clock):
            self.clock, self.txns = clock, []
    
        def deposit(self, amount):
            if amount <= 0:
                raise ValueError("amount must be positive")
            self.txns.append((self.clock(), amount))
    
        def withdraw(self, amount):
            if amount <= 0 or amount > self.balance():
                raise ValueError("invalid withdrawal")
            self.txns.append((self.clock(), -amount))
    
        def balance(self):
            return sum(a for _, a in self.txns)
    
        def statement(self):
            rows, bal = [], 0
            for date, amt in self.txns:
                bal += amt
                rows.append(f"{date} | {amt:+d} | {bal}")
            return ["date | amount | balance"] + rows[::-1]
  10. 10

    Refactor a function that prints a rental statement with three movie types and price rules (the classic Rental kata) so adding a new type needs no edits to existing branches.

    hard

    Replace the switch on type with polymorphism: a Price strategy per movie type with a method that returns the charge for the days rented, and the statement loops over rentals asking each for its charge. Write characterisation tests over the old output first, extract the charge calculation into a method, move it onto the rental, then introduce the strategy classes one at a time keeping tests green. Adding a new type then means adding a class. Mistake: rewriting everything at once without a safety net.

    java
    interface Price { double charge(int days); }
    
    class Regular implements Price {
        public double charge(int days) { return days > 2 ? 2 + (days - 2) * 1.5 : 2; }
    }
    class NewRelease implements Price {
        public double charge(int days) { return days * 3.0; }
    }
    class Childrens implements Price {
        public double charge(int days) { return days > 3 ? 1.5 + (days - 3) * 1.5 : 1.5; }
    }
    // statement loop: total += rental.price().charge(rental.days());

Frequently asked questions

What katas should I practise for Thoughtworks?

Mars Rover, bowling, game of life, roman numerals, string calculator, tic-tac-toe, word wrap and bank account. Do each test-first, in your main language.

Is the exercise live or take-home?

A third-party guide describes a role assessment that is often pair programming. Formats vary by role, so confirm with your recruiter.

How much should I test?

Enough to show the behaviour: one test per rule and one per edge case, written before the code. Tests are read by the interviewer as design documentation.

Do I need design patterns?

Know a few, such as Strategy and Factory, and apply them only when a refactor calls for one. Over-engineering a kata counts against you.

Are these real Thoughtworks tasks?

No, they are practice katas in the same spirit, not copies of any assessment.

Sources

Related guides

More in Company Interview Questions

See all in this section