Autocoder

UBS coding round questions with solutions

Last updated 2026-11-19

UBS graduate technology assessments are commonly described as coding problems of medium difficulty plus some technical MCQs. Heaps, DP, in-place array tricks and tree traversals are all reasonable practice for that level, along with finance-flavoured streaming problems such as a running median and moving average. The ten problems below follow that style. None is a recalled question.

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

StyleMedium arrays, trees, heaps, DP, streaming, SQL, MCQs
Languages herePython, Java, SQL
Problems7 coding, 1 SQL, 2 MCQ
LevelEasy to hard

How to approach this set

Several of these problems have an in-place or constant-space follow-up. Solve them first with extra space, confirm correctness, then tighten, because a correct O(n) space answer scores more than a broken O(1) one.

Streaming problems such as the running median depend on picking the right two structures, so draw the state of both heaps after each insert on a small example. See dynamic programming interview questions and how to crack an online assessment.

UBS coding round questions with solutions: questions with worked answers

  1. 1

    Maximum product subarray: find the contiguous subarray with the largest product.

    medium

    A negative number can turn the smallest product into the largest, so track both the maximum and minimum product ending at each index. For each value x, the new max is the largest of x, max x times x and min times x; the new min is the smallest of the same three. The answer is the best max seen. Time O(n), space O(1). Mistake: copying Kadane's sum recurrence, which ignores negatives and zeros.

    python
    def max_product(a):
        hi = lo = best = a[0]
        for x in a[1:]:
            cands = (x, hi * x, lo * x)
            hi, lo = max(cands), min(cands)
            best = max(best, hi)
        return best
    java
    class Solution {
        static int maxProduct(int[] a) {
            int hi = a[0], lo = a[0], best = a[0];
            for (int i = 1; i < a.length; i++) {
                int x = a[i], p = hi * x, q = lo * x;
                hi = Math.max(x, Math.max(p, q));
                lo = Math.min(x, Math.min(p, q));
                best = Math.max(best, hi);
            }
            return best;
        }
    }
  2. 2

    Next permutation: rearrange numbers into the next lexicographically greater arrangement, in place.

    medium

    Find the rightmost index i where a[i] < a[i+1]. If none exists, reverse the whole array (it was the last permutation). Otherwise find the rightmost j with a[j] > a[i], swap a[i] and a[j], then reverse the suffix after i. Time O(n), space O(1). Example: 1 2 3 becomes 1 3 2, and 3 2 1 becomes 1 2 3. Mistake: sorting the suffix (O(n log n)) when it is already in descending order and only needs reversing.

    python
    def next_permutation(a):
        i = len(a) - 2
        while i >= 0 and a[i] >= a[i + 1]:
            i -= 1
        if i >= 0:
            j = len(a) - 1
            while a[j] <= a[i]:
                j -= 1
            a[i], a[j] = a[j], a[i]
        a[i + 1:] = reversed(a[i + 1:])
    java
    class Solution {
        static void nextPermutation(int[] a) {
            int i = a.length - 2;
            while (i >= 0 && a[i] >= a[i + 1]) i--;
            if (i >= 0) {
                int j = a.length - 1;
                while (a[j] <= a[i]) j--;
                int t = a[i]; a[i] = a[j]; a[j] = t;
            }
            for (int l = i + 1, r = a.length - 1; l < r; l++, r--) { int t = a[l]; a[l] = a[r]; a[r] = t; }
        }
    }
  3. 3

    Binary tree right side view: the values visible when looking at the tree from the right.

    medium

    Do a level-order traversal and record the last node of each level. Alternatively run a DFS that visits the right child first and records the first node seen at each depth. Time O(n), space O(w) for BFS or O(h) for DFS. Mistake: only following right children, which misses a level where the right subtree is shorter than the left.

    python
    from collections import deque
    def right_view(root):
        out, q = [], deque([root] if root else [])
        while q:
            for _ in range(len(q)):
                n = q.popleft()          # the last node popped is the rightmost
                if n.left: q.append(n.left)
                if n.right: q.append(n.right)
            out.append(n.val)
        return out
    java
    import java.util.*;
    class Solution {
        static class TreeNode { int val; TreeNode left, right; }
        static List<Integer> rightView(TreeNode root) {
            List<Integer> out = new ArrayList<>();
            if (root == null) return out;
            Queue<TreeNode> q = new ArrayDeque<>();
            q.add(root);
            while (!q.isEmpty()) {
                int n = q.size();
                for (int i = 0; i < n; i++) {
                    TreeNode cur = q.poll();
                    if (i == n - 1) out.add(cur.val);
                    if (cur.left != null) q.add(cur.left);
                    if (cur.right != null) q.add(cur.right);
                }
            }
            return out;
        }
    }
  4. 4

    Running median of a stream of numbers.

    hard

    Keep two heaps: a max-heap for the lower half and a min-heap for the upper half, balanced so their sizes differ by at most one. Insert into the lower half, move its largest into the upper half, and rebalance if the upper half is larger. The median is the top of the larger heap, or the average of the two tops when sizes are equal. Insert O(log n), median O(1), space O(n). In Python, store negated values in a min-heap to simulate a max-heap.

    python
    import heapq
    class RunningMedian:
        def __init__(self):
            self.lo, self.hi = [], []          # lo is a max-heap (negated)
        def add(self, x):
            heapq.heappush(self.lo, -x)
            heapq.heappush(self.hi, -heapq.heappop(self.lo))
            if len(self.hi) > len(self.lo):
                heapq.heappush(self.lo, -heapq.heappop(self.hi))
        def median(self):
            if len(self.lo) > len(self.hi):
                return float(-self.lo[0])
            return (-self.lo[0] + self.hi[0]) / 2
    java
    import java.util.*;
    class RunningMedian {
        private final PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder());
        private final PriorityQueue<Integer> hi = new PriorityQueue<>();
        void add(int x) {
            lo.add(x);
            hi.add(lo.poll());
            if (hi.size() > lo.size()) lo.add(hi.poll());
        }
        double median() {
            return lo.size() > hi.size() ? lo.peek() : (lo.peek() + hi.peek()) / 2.0;
        }
    }
  5. 5

    Best time to buy and sell a stock with a one-day cooldown after selling, with unlimited transactions.

    hard

    Use three states per day: hold (own a share), sold (just sold today) and rest (no share, free to buy). Transitions: hold = max(hold, rest - price), sold = hold_prev + price, rest = max(rest, sold_prev). The answer is the larger of sold and rest on the last day. Time O(n), space O(1). Mistake: updating the states in place in the wrong order, so that today's value uses today's other state rather than yesterday's.

    python
    def max_profit(prices):
        hold, sold, rest = float('-inf'), 0, 0
        for p in prices:
            prev_sold = sold
            sold = hold + p
            hold = max(hold, rest - p)
            rest = max(rest, prev_sold)
        return max(sold, rest)
    java
    class Solution {
        static int maxProfit(int[] prices) {
            int hold = Integer.MIN_VALUE / 2, sold = 0, rest = 0;
            for (int p : prices) {
                int prevSold = sold;
                sold = hold + p;
                hold = Math.max(hold, rest - p);
                rest = Math.max(rest, prevSold);
            }
            return Math.max(sold, rest);
        }
    }
  6. 6

    Set matrix zeroes: if a cell is 0, set its entire row and column to 0, in place.

    medium

    Use the first row and first column as markers. First record whether the first row and first column themselves contain a zero. Then for every other cell that is zero, mark its row and column in the first row and column. Next zero out cells based on those markers, and finally clear the first row and column if they originally contained a zero. Time O(mn), space O(1). Mistake: zeroing as you scan, which spreads the zeros to cells that were not originally zero.

    python
    def set_zeroes(m):
        R, C = len(m), len(m[0])
        row0 = any(m[0][j] == 0 for j in range(C))
        col0 = any(m[i][0] == 0 for i in range(R))
        for i in range(1, R):
            for j in range(1, C):
                if m[i][j] == 0:
                    m[i][0] = m[0][j] = 0
        for i in range(1, R):
            for j in range(1, C):
                if m[i][0] == 0 or m[0][j] == 0:
                    m[i][j] = 0
        if row0:
            for j in range(C): m[0][j] = 0
        if col0:
            for i in range(R): m[i][0] = 0
    java
    class Solution {
        static void setZeroes(int[][] m) {
            int R = m.length, C = m[0].length;
            boolean row0 = false, col0 = false;
            for (int j = 0; j < C; j++) if (m[0][j] == 0) row0 = true;
            for (int i = 0; i < R; i++) if (m[i][0] == 0) col0 = true;
            for (int i = 1; i < R; i++)
                for (int j = 1; j < C; j++)
                    if (m[i][j] == 0) { m[i][0] = 0; m[0][j] = 0; }
            for (int i = 1; i < R; i++)
                for (int j = 1; j < C; j++)
                    if (m[i][0] == 0 || m[0][j] == 0) m[i][j] = 0;
            if (row0) for (int j = 0; j < C; j++) m[0][j] = 0;
            if (col0) for (int i = 0; i < R; i++) m[i][0] = 0;
        }
    }
  7. 7

    Moving average of the last k values from a data stream.

    easy

    Keep a queue holding the last k values and a running sum. On each new value, add it to the queue and the sum, and if the queue is longer than k remove the oldest and subtract it. Return sum divided by the queue length. Each update is O(1), space O(k). Mistake: recomputing the sum over the window on each call, which is O(k) and slows down for large windows, and integer division when the average should be a decimal.

    python
    from collections import deque
    class MovingAverage:
        def __init__(self, k):
            self.k, self.q, self.total = k, deque(), 0
        def next(self, x):
            self.q.append(x)
            self.total += x
            if len(self.q) > self.k:
                self.total -= self.q.popleft()
            return self.total / len(self.q)
    java
    import java.util.*;
    class MovingAverage {
        private final int k;
        private final Deque<Integer> q = new ArrayDeque<>();
        private long total = 0;
        MovingAverage(int k) { this.k = k; }
        double next(int x) {
            q.addLast(x);
            total += x;
            if (q.size() > k) total -= q.pollFirst();
            return (double) total / q.size();
        }
    }
  8. 8

    SQL: for each client, show their total trade value and its percentage of the overall total.

    medium

    Aggregate by client, then divide by a window SUM over the aggregated rows, which is computed after GROUP BY. SUM(SUM(value)) OVER () looks odd but is valid: the inner SUM is the group aggregate and the outer one is a window over all groups. Cast to decimal before dividing to avoid integer division. See SQL window functions interview questions.

    sql
    SELECT client_id,
           SUM(value) AS total_value,
           ROUND(100.0 * SUM(value) / SUM(SUM(value)) OVER (), 2) AS pct_of_total
    FROM Trades
    GROUP BY client_id
    ORDER BY total_value DESC;
  9. 9

    MCQ: what is the time complexity of list.insert(0, x) in Python for a list of n items, and what is the better structure for a queue?

    easy

    O(n), because every existing element must shift one position to the right. collections.deque supports O(1) appends and pops at both ends, so use it for queues and sliding windows. Python's list.pop(0) has the same O(n) cost. A frequent trap in timed tests is using a list as a queue in a BFS over a large graph, which turns an O(V + E) algorithm into a much slower one.

  10. 10

    MCQ: in Java, which of these allows a null key: HashMap, Hashtable, TreeMap or ConcurrentHashMap?

    easy

    Only HashMap allows one null key (and null values). Hashtable and ConcurrentHashMap throw NullPointerException for null keys and values, partly because null would make 'absent' ambiguous in concurrent code. TreeMap with natural ordering throws on a null key because it cannot compare it. If a question lists LinkedHashMap, it behaves like HashMap and also allows one null key.

Frequently asked questions

How hard is the UBS coding test?

It is commonly described as medium difficulty with some easier and some harder problems. This set covers that range.

Does it include SQL?

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

Do I need finance knowledge for the coding round?

No. The coding problems are general. Finance-flavoured examples here are only for context.

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