Autocoder

Mastercard coding round questions with solutions

Last updated 2026-11-19

Mastercard graduate and early-career assessments are commonly described as an online test with coding problems at easy to medium level and technical or aptitude MCQs. The set below follows that style with eight coding problems, covering strings, two pointers, greedy, DP and SQL, plus two MCQs. None is a recalled question.

Each answer has the approach, complexity, the usual mistake and runnable Python and Java. For the interviews, see Mastercard interview questions.

StyleEasy to medium arrays, greedy, DP, SQL, plus MCQs
Languages herePython, Java, SQL
Problems8 coding, 2 MCQ-style
LevelEasy to hard

How to approach this set

Greedy problems such as gas station and container with most water are usually short once you find the invariant, so spend your time on why the greedy choice is safe. If you cannot justify it in one sentence, test it against a small counterexample.

For the MCQs, practise recalling language behaviour such as Integer caching and using complements in probability. See how to crack a technical MCQ test and how to crack an online assessment.

Mastercard coding round questions with solutions: questions with worked answers

  1. 1

    Convert a Roman numeral string to an integer.

    easy

    Scan left to right. A symbol smaller than the one after it is subtracted (IV is 4), otherwise it is added. Use a map of the seven symbols. Time O(n), space O(1). The mistake is hard-coding the six subtractive pairs and missing cases; the compare-with-next rule handles them all. Assume a valid numeral, and state it.

    python
    def roman_to_int(s):
        v = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        total = 0
        for i, ch in enumerate(s):
            if i + 1 < len(s) and v[ch] < v[s[i + 1]]:
                total -= v[ch]
            else:
                total += v[ch]
        return total
    java
    import java.util.*;
    class Solution {
        static int romanToInt(String s) {
            Map<Character, Integer> v = Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
            int total = 0;
            for (int i = 0; i < s.length(); i++) {
                int cur = v.get(s.charAt(i));
                if (i + 1 < s.length() && cur < v.get(s.charAt(i + 1))) total -= cur;
                else total += cur;
            }
            return total;
        }
    }
  2. 2

    Container with most water: choose two lines to maximise the area they enclose with the x-axis.

    medium

    Two pointers at both ends. The area is the smaller height times the distance; move the pointer at the shorter line inward, because moving the taller one can only reduce the width without raising the limiting height. Time O(n), space O(1). Brute force over all pairs is O(n^2). Mistake: moving the taller pointer, which loses the optimal pair.

    python
    def max_area(h):
        l, r, best = 0, len(h) - 1, 0
        while l < r:
            best = max(best, min(h[l], h[r]) * (r - l))
            if h[l] < h[r]:
                l += 1
            else:
                r -= 1
        return best
    java
    class Solution {
        static int maxArea(int[] h) {
            int l = 0, r = h.length - 1, best = 0;
            while (l < r) {
                best = Math.max(best, Math.min(h[l], h[r]) * (r - l));
                if (h[l] < h[r]) l++; else r--;
            }
            return best;
        }
    }
  3. 3

    Length of the longest strictly increasing subsequence in O(n log n).

    hard

    Maintain a list tails where tails[k] is the smallest possible last value of an increasing subsequence of length k + 1. For each number, binary search for the first tail that is greater than or equal to it and replace it, or append if none. The list length is the answer. Time O(n log n), space O(n). The list is not itself the subsequence. The O(n^2) DP is acceptable for small n; see dynamic programming interview questions.

    python
    from bisect import bisect_left
    def lis(a):
        tails = []
        for x in a:
            i = bisect_left(tails, x)
            if i == len(tails):
                tails.append(x)
            else:
                tails[i] = x
        return len(tails)
    java
    import java.util.*;
    class Solution {
        static int lis(int[] a) {
            int[] tails = new int[a.length];
            int size = 0;
            for (int x : a) {
                int lo = 0, hi = size;
                while (lo < hi) {
                    int mid = (lo + hi) / 2;
                    if (tails[mid] < x) lo = mid + 1; else hi = mid;
                }
                tails[lo] = x;
                if (lo == size) size++;
            }
            return size;
        }
    }
  4. 4

    Gas station: stations in a circle have gas[i] fuel and cost[i] to reach the next. Find the starting index that completes the circuit, or -1.

    medium

    If total gas is less than total cost, no start works. Otherwise there is exactly one answer: scan once keeping the current tank; whenever it goes negative, no station from the start up to here can be the start, so reset the start to the next index and the tank to 0. Time O(n), space O(1). The mistake is simulating from every start, which is O(n^2).

    python
    def can_complete(gas, cost):
        if sum(gas) < sum(cost):
            return -1
        start = tank = 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:
                start, tank = i + 1, 0
        return start
    java
    class Solution {
        static int canComplete(int[] gas, int[] cost) {
            int total = 0, tank = 0, start = 0;
            for (int i = 0; i < gas.length; i++) {
                int d = gas[i] - cost[i];
                total += d;
                tank += d;
                if (tank < 0) { start = i + 1; tank = 0; }
            }
            return total < 0 ? -1 : start;
        }
    }
  5. 5

    Implement pow(x, n) for integer n, including negative n.

    medium

    Fast exponentiation: square the base and halve the exponent, multiplying into the result when the exponent bit is 1. Time O(log n), space O(1). For negative n, invert the base and use |n|. In Java convert n to long before negating, since -Integer.MIN_VALUE overflows. The naive loop is O(n) and times out for large n.

    python
    def my_pow(x, n):
        if n < 0:
            x, n = 1 / x, -n
        r = 1.0
        while n:
            if n & 1:
                r *= x
            x *= x
            n >>= 1
        return r
    java
    class Solution {
        static double myPow(double x, int n) {
            long e = n;
            if (e < 0) { x = 1 / x; e = -e; }
            double r = 1.0;
            while (e > 0) {
                if ((e & 1) == 1) r *= x;
                x *= x;
                e >>= 1;
            }
            return r;
        }
    }
  6. 6

    Task scheduler: tasks are letters, the same letter needs n idle slots between runs. Find the minimum time to finish.

    medium

    The most frequent task decides the frame: with max frequency f there are f - 1 gaps of length n + 1, and the last row holds every task that has frequency f. The minimum time is the larger of the number of tasks and (f - 1) x (n + 1) + (count of tasks with frequency f). Time O(n), space O(1) for 26 letters. Mistake: forgetting the max with the task count, which undercounts when there are many distinct tasks and no idle time is needed.

    python
    from collections import Counter
    def least_interval(tasks, n):
        c = Counter(tasks)
        f = max(c.values())
        top = sum(1 for v in c.values() if v == f)
        return max(len(tasks), (f - 1) * (n + 1) + top)
    java
    class Solution {
        static int leastInterval(char[] tasks, int n) {
            int[] c = new int[26];
            for (char t : tasks) c[t - 'A']++;
            int f = 0, top = 0;
            for (int v : c) f = Math.max(f, v);
            for (int v : c) if (v == f) top++;
            return Math.max(tasks.length, (f - 1) * (n + 1) + top);
        }
    }
  7. 7

    Find the duplicate number in an array of n + 1 integers in 1..n without modifying it, in O(1) space.

    hard

    Treat index i as pointing to a[i]. Because a value repeats, two indices point to the same place, so the path contains a cycle and its entrance is the duplicate. Use Floyd's two-phase algorithm: find a meeting point with slow and fast pointers, then restart one pointer from the start and move both one step at a time; they meet at the cycle entrance. Time O(n), space O(1). Mistake: keeping the fast pointer's double speed in the second phase; after the restart, both pointers move one step at a time.

    python
    def find_duplicate(a):
        slow = fast = a[0]
        while True:
            slow = a[slow]
            fast = a[a[fast]]
            if slow == fast:
                break
        slow = a[0]
        while slow != fast:
            slow = a[slow]
            fast = a[fast]
        return slow
    java
    class Solution {
        static int findDuplicate(int[] a) {
            int slow = a[0], fast = a[0];
            do { slow = a[slow]; fast = a[a[fast]]; } while (slow != fast);
            slow = a[0];
            while (slow != fast) { slow = a[slow]; fast = a[fast]; }
            return slow;
        }
    }
  8. 8

    SQL: return the most recent transaction for each card.

    easy

    Number each card's transactions by date descending with ROW_NUMBER and keep row 1. Add the transaction id as a tie-breaker so exactly one row is returned when two share a timestamp. A correlated subquery with MAX(txn_time) is the alternative, but it returns ties twice. See SQL window functions interview questions.

    sql
    SELECT card_id, txn_id, txn_time, amount
    FROM (
      SELECT t.*, ROW_NUMBER() OVER (PARTITION BY card_id ORDER BY txn_time DESC, txn_id DESC) AS rn
      FROM Transactions t
    ) x
    WHERE rn = 1;
  9. 9

    Java MCQ: Integer a = 127, b = 127, c = 128, d = 128. What are (a == b) and (c == d)?

    easy

    True and false. Autoboxing uses Integer.valueOf, which caches instances for values from -128 to 127, so a and b are the same object while 128 creates two distinct objects. Always compare boxed values with equals. The cache range is the point; the same behaviour applies to Long, Short and Byte, but not to Double or Float.

  10. 10

    Probability MCQ: a fair die is rolled four times. What is the probability of at least one six?

    medium

    Use the complement. The chance of no six in four rolls is (5/6)^4 = 625/1296, so at least one six has probability 1 - 625/1296 = 671/1296, about 0.518. Multiplying 4 x 1/6 = 2/3 overcounts because the events overlap. The complement trick is the general method for 'at least one' questions.

Frequently asked questions

How hard is the Mastercard coding test?

It is commonly described as easy to medium with occasional harder problems. This set covers that range.

Are there MCQs?

Some cycles are reported to include technical or aptitude MCQs. Formats change, so read your invitation.

Is SQL tested?

Technology roles are sometimes reported to include SQL. Practise window functions and aggregation.

Are these the real questions?

No. They are original practice problems in the style of the topics the round commonly covers.

Related guides

More in Company Interview Questions

See all in this section