Autocoder

Microsoft Coding Round Questions with Solutions in Python and Java

Last updated 2026-11-19

Microsoft coding rounds favour clean pointer and tree manipulation, in-place array and matrix work, and graph copying. These ten problems cover that ground, from Kadane's algorithm to reversing nodes in groups.

Attempt each problem first and compare. Python and Java solutions are given with complexity and the mistakes interviewers see most.

Problems10, easy to hard
LanguagesPython and Java
PatternsLinked lists, trees, matrices, graphs
Round formatOpen-ended coding, per Microsoft

Style of Microsoft coding questions

Microsoft's guidance describes an open-ended coding problem in technical rounds, and the problems commonly practised for it lean on linked lists, trees, matrices and graphs with clear in-place requirements. These ten follow that style. They are practice problems, not real interview content.

Pair this page with Microsoft interview questions for the fundamentals and behavioural side.

Mistakes that show up repeatedly

Hiring status

For current Microsoft roles and dates, see Microsoft hiring and the company's own site, careers.microsoft.com. Microsoft announced a voluntary buyout for about 60,000 eligible employees on 26 October 2026, so check the careers site rather than relying on old drive posts.

Microsoft Coding Round Questions with Solutions in Python and Java: questions with worked answers

  1. 1

    Reverse Nodes in k-Group.

    hard

    Check that k nodes remain; if so, reverse exactly k nodes in place and connect the reversed block to the previous tail and to the result of processing the rest. If fewer than k remain, leave them as they are. Time O(n), space O(1) iteratively. Mistakes: reversing a final short group, and losing the pointer to the node that becomes the group's tail.

    python
    def reverse_k_group(head, k):
        dummy = ListNode(0); dummy.next = head
        group_prev = dummy
        while True:
            kth = group_prev
            for _ in range(k):
                kth = kth.next
                if not kth: return dummy.next
            group_next = kth.next
            prev, cur = group_next, group_prev.next
            while cur is not group_next:
                cur.next, prev, cur = prev, cur, cur.next
            tmp = group_prev.next
            group_prev.next = kth
            group_prev = tmp
    java
    class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
    class Solution {
        ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(0); dummy.next = head;
            ListNode gp = dummy;
            while (true) {
                ListNode kth = gp;
                for (int i = 0; i < k && kth != null; i++) kth = kth.next;
                if (kth == null) return dummy.next;
                ListNode gn = kth.next, prev = gn, cur = gp.next;
                while (cur != gn) { ListNode nx = cur.next; cur.next = prev; prev = cur; cur = nx; }
                ListNode tmp = gp.next; gp.next = kth; gp = tmp;
            }
        }
    }
  2. 2

    Validate a Binary Search Tree.

    medium

    Pass down an allowed open range (low, high). Each node's value must lie strictly inside the range; the left subtree gets (low, node) and the right gets (node, high). Time O(n), space O(h). Mistake: comparing only a node with its immediate children, which accepts trees where a deeper node violates an ancestor. In Java use Long bounds or null to handle Integer.MIN_VALUE nodes.

    python
    def is_valid_bst(root, lo=float('-inf'), hi=float('inf')):
        if not root: return True
        if not (lo < root.val < hi): return False
        return is_valid_bst(root.left, lo, root.val) and is_valid_bst(root.right, root.val, hi)
    java
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        boolean isValid(TreeNode n, long lo, long hi) {
            if (n == null) return true;
            if (n.val <= lo || n.val >= hi) return false;
            return isValid(n.left, lo, n.val) && isValid(n.right, n.val, hi);
        }
        boolean isValidBST(TreeNode r) { return isValid(r, Long.MIN_VALUE, Long.MAX_VALUE); }
    }
  3. 3

    Lowest Common Ancestor of a binary tree (no ordering).

    medium

    Recurse: return the node if it is null or one of the targets; recurse left and right. If both sides return non-null, the current node is the LCA; otherwise return whichever side is non-null. Time O(n), space O(h). This handles the case where one target is the ancestor of the other. Mistake: using the BST ordering shortcut on an unordered tree.

    python
    def lca(root, p, q):
        if not root or root is p or root is q: return root
        l, r = lca(root.left, p, q), lca(root.right, p, q)
        return root if l and r else (l or r)
    java
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
            if (root == null || root == p || root == q) return root;
            TreeNode l = lca(root.left, p, q), r = lca(root.right, p, q);
            return (l != null && r != null) ? root : (l != null ? l : r);
        }
    }
  4. 4

    Spiral Matrix: return elements in spiral order.

    medium

    Maintain four boundaries (top, bottom, left, right). Walk the top row left to right and shrink top, the right column and shrink right, then the bottom row (if rows remain) and the left column (if columns remain). Time O(m n), space O(1) beyond output. Mistake: forgetting the checks before the last two walks, which duplicates elements for single-row or single-column matrices.

    python
    def spiral(m):
        out = []
        t, b, l, r = 0, len(m) - 1, 0, len(m[0]) - 1
        while t <= b and l <= r:
            out += m[t][l:r+1]; t += 1
            for i in range(t, b + 1): out.append(m[i][r])
            r -= 1
            if t <= b:
                out += m[b][l:r+1][::-1]; b -= 1
            if l <= r:
                for i in range(b, t - 1, -1): out.append(m[i][l])
                l += 1
        return out
    java
    import java.util.*;
    class Solution {
        List<Integer> spiral(int[][] m) {
            List<Integer> out = new ArrayList<>();
            int t = 0, b = m.length - 1, l = 0, r = m[0].length - 1;
            while (t <= b && l <= r) {
                for (int j = l; j <= r; j++) out.add(m[t][j]);
                t++;
                for (int i = t; i <= b; i++) out.add(m[i][r]);
                r--;
                if (t <= b) { for (int j = r; j >= l; j--) out.add(m[b][j]); b--; }
                if (l <= r) { for (int i = b; i >= t; i--) out.add(m[i][l]); l++; }
            }
            return out;
        }
    }
  5. 5

    Rotate Image: rotate an n by n matrix 90 degrees clockwise in place.

    medium

    Transpose the matrix (swap m[i][j] with m[j][i] for j > i), then reverse each row. Time O(n squared), space O(1). Counter-clockwise rotation is transpose then reverse each column, or reverse rows first then transpose. Mistake: swapping all pairs during the transpose, which undoes the work.

    python
    def rotate(m):
        n = len(m)
        for i in range(n):
            for j in range(i + 1, n):
                m[i][j], m[j][i] = m[j][i], m[i][j]
        for row in m: row.reverse()
    java
    class Solution {
        void rotate(int[][] m) {
            int n = m.length;
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++) { int t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t; }
            for (int[] row : m)
                for (int i = 0, j = n - 1; i < j; i++, j--) { int t = row[i]; row[i] = row[j]; row[j] = t; }
        }
    }
  6. 6

    Add Two Numbers stored as reversed linked lists of digits.

    medium

    Walk both lists together with a carry. At each step add the two digits (0 if a list has ended) and the carry, append digit sum % 10 and carry sum // 10. Continue while either list or the carry remains. Time O(max(m, n)), space O(1) beyond output. Mistake: dropping a final carry, as in 99 + 1.

    python
    def add_two(a, b):
        dummy = tail = ListNode(0)
        carry = 0
        while a or b or carry:
            s = carry + (a.val if a else 0) + (b.val if b else 0)
            carry, d = divmod(s, 10)
            tail.next = ListNode(d); tail = tail.next
            a = a.next if a else None
            b = b.next if b else None
        return dummy.next
    java
    class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
    class Solution {
        ListNode addTwo(ListNode a, ListNode b) {
            ListNode dummy = new ListNode(0), tail = dummy;
            int carry = 0;
            while (a != null || b != null || carry != 0) {
                int s = carry + (a != null ? a.val : 0) + (b != null ? b.val : 0);
                carry = s / 10;
                tail.next = new ListNode(s % 10); tail = tail.next;
                if (a != null) a = a.next;
                if (b != null) b = b.next;
            }
            return dummy.next;
        }
    }
  7. 7

    Clone Graph: deep copy a connected undirected graph.

    medium

    Traverse the graph with DFS or BFS while a hash map from original node to its copy ensures each node is copied once and handles cycles. Create the copy when first seen, then add copies of neighbours. Time O(V + E), space O(V). Mistake: creating a new node on every visit, which loops forever on cycles.

    python
    def clone(node):
        if not node: return None
        copies = {node: Node(node.val)}
        stack = [node]
        while stack:
            u = stack.pop()
            for v in u.neighbors:
                if v not in copies:
                    copies[v] = Node(v.val)
                    stack.append(v)
                copies[u].neighbors.append(copies[v])
        return copies[node]
    java
    import java.util.*;
    class Node { int val; List<Node> neighbors = new ArrayList<>(); Node(int v) { val = v; } }
    class Solution {
        Node clone(Node node) {
            if (node == null) return null;
            Map<Node, Node> copies = new HashMap<>();
            copies.put(node, new Node(node.val));
            Deque<Node> st = new ArrayDeque<>();
            st.push(node);
            while (!st.isEmpty()) {
                Node u = st.pop();
                for (Node v : u.neighbors) {
                    if (!copies.containsKey(v)) { copies.put(v, new Node(v.val)); st.push(v); }
                    copies.get(u).neighbors.add(copies.get(v));
                }
            }
            return copies.get(node);
        }
    }
  8. 8

    Maximum Subarray (Kadane's algorithm).

    easy

    Track the best sum ending at the current index: either extend the previous subarray or start fresh at this element, cur = max(x, cur + x), and keep the maximum seen. Time O(n), space O(1). Mistake: initialising the answer to 0, which fails when all numbers are negative; start from the first element.

    python
    def max_subarray(a):
        cur = best = a[0]
        for x in a[1:]:
            cur = max(x, cur + x)
            best = max(best, cur)
        return best
    java
    class Solution {
        int maxSubArray(int[] a) {
            int cur = a[0], best = a[0];
            for (int i = 1; i < a.length; i++) {
                cur = Math.max(a[i], cur + a[i]);
                best = Math.max(best, cur);
            }
            return best;
        }
    }
  9. 9

    Set Matrix Zeroes in O(1) extra space.

    medium

    Use the first row and first column as markers. First record whether the first row and column themselves contain a zero. Then for every other cell that is zero, mark its row and column header. Zero the interior using the markers, and finally clear the first row and column if flagged. Time O(m n), space O(1). Mistake: zeroing as you scan, which spreads new zeros that look original.

    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 {
        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;
        }
    }
  10. 10

    Flatten a Binary Tree to a linked list in pre-order, in place.

    medium

    Iterate: for each node with a left child, find the rightmost node of the left subtree, attach the current right subtree there, move the left subtree to the right, and set left to null; then step to the right child. Time O(n), space O(1) (a Morris-style approach). The recursive reverse post-order version is simpler but uses O(h) stack. Mistake: forgetting to null out the left pointer.

    python
    def flatten(root):
        cur = root
        while cur:
            if cur.left:
                p = cur.left
                while p.right: p = p.right
                p.right = cur.right
                cur.right, cur.left = cur.left, None
            cur = cur.right
    java
    class TreeNode { int val; TreeNode left, right; }
    class Solution {
        void flatten(TreeNode root) {
            TreeNode cur = root;
            while (cur != null) {
                if (cur.left != null) {
                    TreeNode p = cur.left;
                    while (p.right != null) p = p.right;
                    p.right = cur.right;
                    cur.right = cur.left; cur.left = null;
                }
                cur = cur.right;
            }
        }
    }

Frequently asked questions

Which language should I use for Microsoft coding?

Choose the language you code fastest in. Both Python and Java are common for these problems.

Are Microsoft problems harder than Amazon ones?

Both mostly use medium problems with follow-ups. Microsoft problems often stress clean in-place manipulation and explaining your reasoning.

Do I need to memorise Morris traversal?

It is a useful O(1)-space idea, as in the flatten problem, but understanding the stack-based version first is more important.

Sources

Related guides

More in Company Interview Questions

See all in this section