Autocoder

Mphasis Coding Round Questions with Solutions

Last updated 2026-11-19

This page gives ten data-structure and recursion problems for application-development style tests, each with Python and Java solutions, complexity and mistakes. Mphasis has not published its test content, so this is practice rather than a claim about a particular paper.

Read Mphasis interview questions for the spoken side and how to crack the DSA coding round for strategy.

LevelEasy to medium
LanguagesPython and Java shown
TopicsLinked lists, trees, recursion, sorting

What these Mphasis-style problems cover

Mphasis does not publish its test content, so we do not claim a particular format. These ten problems are general practice for application-development hiring: classic structures built from scratch (queue from stacks, linked-list pointer tricks), tree traversals, recursion and backtracking, and a hand-written sort. They are the kind of problems a technical interviewer uses to see whether you understand data structures rather than only library calls.

Practice approach

Mphasis Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Implement a queue using two stacks

    medium

    Push onto an input stack. For dequeue or peek, if the output stack is empty move every element from input to output, reversing order, then pop from output. Each element moves at most once. Complexity: amortised O(1) per operation, O(n) space. Common mistakes: moving elements on every dequeue (O(n) each time) and moving while output still has items, which breaks order.

    python
    class MyQueue:
        def __init__(self): self.i, self.o = [], []
        def push(self, x): self.i.append(x)
        def _move(self):
            if not self.o:
                while self.i: self.o.append(self.i.pop())
        def pop(self): self._move(); return self.o.pop()
        def peek(self): self._move(); return self.o[-1]
    q = MyQueue(); q.push(1); q.push(2)
    print(q.pop(), q.peek())  # 1 2
    java
    import java.util.*;
    class MyQueue {
        private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();
        void push(int x) { in.push(x); }
        private void move() { if (out.isEmpty()) while (!in.isEmpty()) out.push(in.pop()); }
        int pop() { move(); return out.pop(); }
        int peek() { move(); return out.peek(); }
    }
  2. 2

    Remove the Nth node from the end of a linked list

    medium

    Use two pointers separated by N steps from a dummy head; when the leading pointer reaches the end, the trailing one stands just before the node to remove. Complexity: O(L) time, O(1) space. Common mistakes: not using a dummy node, so removing the head fails, and being off by one in the gap.

    python
    class Node:
        def __init__(self, v, nxt=None): self.v, self.next = v, nxt
    def remove_nth(head, n):
        d = Node(0, head); fast = slow = d
        for _ in range(n): fast = fast.next
        while fast.next:
            fast, slow = fast.next, slow.next
        slow.next = slow.next.next
        return d.next
    h = remove_nth(Node(1, Node(2, Node(3, Node(4)))), 2)
    out = []
    while h: out.append(h.v); h = h.next
    print(out)  # [1, 2, 4]
    java
    class Solution {
        static class Node { int v; Node next; Node(int v) { this.v = v; } }
        static Node removeNth(Node head, int n) {
            Node d = new Node(0); d.next = head;
            Node fast = d, slow = d;
            for (int i = 0; i < n; i++) fast = fast.next;
            while (fast.next != null) { fast = fast.next; slow = slow.next; }
            slow.next = slow.next.next;
            return d.next;
        }
    }
  3. 3

    Middle node of a linked list

    easy

    Slow and fast pointers: fast moves two steps for each one of slow. When fast reaches the end, slow is at the middle (the second middle for even lengths). Complexity: O(n) time, O(1) space. Common mistakes: counting the length first (two passes) and not stating which middle you return for even lengths.

    python
    class Node:
        def __init__(self, v, nxt=None): self.v, self.next = v, nxt
    def middle(head):
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
        return slow.v
    print(middle(Node(1, Node(2, Node(3, Node(4))))))  # 3
    java
    class Solution {
        static class Node { int v; Node next; Node(int v) { this.v = v; } }
        static int middle(Node head) {
            Node slow = head, fast = head;
            while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
            return slow.v;
        }
    }
  4. 4

    Find all anagram start indices of a pattern in a string

    medium

    Slide a window of the pattern's length over the string, maintaining counts of characters in the window and comparing with the pattern's counts. Update counts incrementally instead of rebuilding. Complexity: O(n) time for a fixed alphabet, O(1) space. Common mistakes: recounting the window each step (O(n * m)) and comparing counters of unequal alphabets inefficiently.

    python
    from collections import Counter
    def find_anagrams(s, p):
        need, win, out = Counter(p), Counter(), []
        for i, ch in enumerate(s):
            win[ch] += 1
            if i >= len(p):
                old = s[i - len(p)]
                win[old] -= 1
                if win[old] == 0: del win[old]
            if win == need: out.append(i - len(p) + 1)
        return out
    print(find_anagrams("cbaebabacd", "abc"))  # [0, 6]
    java
    import java.util.*;
    class Solution {
        static List<Integer> findAnagrams(String s, String p) {
            List<Integer> out = new ArrayList<>();
            int[] need = new int[26], win = new int[26];
            for (char c : p.toCharArray()) need[c - 'a']++;
            for (int i = 0; i < s.length(); i++) {
                win[s.charAt(i) - 'a']++;
                if (i >= p.length()) win[s.charAt(i - p.length()) - 'a']--;
                if (Arrays.equals(need, win)) out.add(i - p.length() + 1);
            }
            return out;
        }
    }
  5. 5

    All subsets (power set)

    medium

    For each element either include it or not, recursing through the array. Iteratively, start with [[]] and for each number append it to copies of all existing subsets. There are 2^n subsets. Complexity: O(n * 2^n) time and output size. Common mistakes: appending the same list object without copying and including duplicates when the input has repeats (sort and skip needed then).

    python
    def subsets(a):
        res = [[]]
        for x in a:
            res += [s + [x] for s in res]
        return res
    print(subsets([1, 2, 3]))
    java
    import java.util.*;
    class Solution {
        static List<List<Integer>> subsets(int[] a) {
            List<List<Integer>> res = new ArrayList<>();
            res.add(new ArrayList<>());
            for (int x : a) {
                int n = res.size();
                for (int i = 0; i < n; i++) {
                    List<Integer> s = new ArrayList<>(res.get(i));
                    s.add(x);
                    res.add(s);
                }
            }
            return res;
        }
    }
  6. 6

    Permutations of distinct numbers

    medium

    Backtrack: at each position try every unused element, mark it used, recurse, then unmark. A result is complete when the path length equals n. Complexity: O(n * n!) time, O(n) recursion. Common mistakes: adding the live path without copying it and forgetting to unmark after recursion.

    python
    def permute(a):
        res, path, used = [], [], [False] * len(a)
        def go():
            if len(path) == len(a): res.append(path[:]); return
            for i, x in enumerate(a):
                if used[i]: continue
                used[i] = True; path.append(x)
                go()
                path.pop(); used[i] = False
        go()
        return res
    print(permute([1, 2, 3]))
    java
    import java.util.*;
    class Solution {
        static List<List<Integer>> permute(int[] a) {
            List<List<Integer>> res = new ArrayList<>();
            go(a, new boolean[a.length], new ArrayList<>(), res);
            return res;
        }
        static void go(int[] a, boolean[] used, List<Integer> path, List<List<Integer>> res) {
            if (path.size() == a.length) { res.add(new ArrayList<>(path)); return; }
            for (int i = 0; i < a.length; i++) {
                if (used[i]) continue;
                used[i] = true; path.add(a[i]);
                go(a, used, path, res);
                path.remove(path.size() - 1); used[i] = false;
            }
        }
    }
  7. 7

    Iterative inorder traversal of a binary tree

    medium

    Use a stack: go as far left as possible pushing nodes, pop one, visit it, then move to its right child. This avoids recursion depth limits. Complexity: O(n) time, O(h) space. Common mistakes: forgetting to move to the right child after visiting, and an infinite loop from not clearing the current pointer.

    python
    class T:
        def __init__(self, v, l=None, r=None): self.v, self.l, self.r = v, l, r
    def inorder(root):
        out, st, cur = [], [], root
        while cur or st:
            while cur: st.append(cur); cur = cur.l
            cur = st.pop(); out.append(cur.v); cur = cur.r
        return out
    print(inorder(T(2, T(1), T(3))))  # [1, 2, 3]
    java
    import java.util.*;
    class Solution {
        static class T { int v; T l, r; T(int v) { this.v = v; } }
        static List<Integer> inorder(T root) {
            List<Integer> out = new ArrayList<>();
            Deque<T> st = new ArrayDeque<>();
            T cur = root;
            while (cur != null || !st.isEmpty()) {
                while (cur != null) { st.push(cur); cur = cur.l; }
                cur = st.pop(); out.add(cur.v); cur = cur.r;
            }
            return out;
        }
    }
  8. 8

    Maximum depth of a binary tree

    easy

    Depth of a node is 1 plus the larger depth of its children, and 0 for an empty tree. Breadth-first counting of levels works without recursion. Complexity: O(n) time, O(h) space. Common mistakes: returning the minimum instead of the maximum and counting edges versus nodes inconsistently.

    python
    class T:
        def __init__(self, v, l=None, r=None): self.v, self.l, self.r = v, l, r
    def depth(n):
        return 0 if not n else 1 + max(depth(n.l), depth(n.r))
    print(depth(T(1, T(2, T(4)), T(3))))  # 3
    java
    class Solution {
        static class T { int v; T l, r; T(int v) { this.v = v; } }
        static int depth(T n) {
            return n == null ? 0 : 1 + Math.max(depth(n.l), depth(n.r));
        }
    }
  9. 9

    Merge sort

    medium

    Split the array in halves, sort each recursively, and merge two sorted halves with two pointers. Use <= when merging to keep it stable. Complexity: O(n log n) time, O(n) space. Common mistakes: copying subarrays repeatedly with slicing in a hot loop and using < in the merge, which loses stability.

    python
    def merge_sort(a):
        if len(a) <= 1: return a
        m = len(a) // 2
        l, r = merge_sort(a[:m]), merge_sort(a[m:])
        out, i, j = [], 0, 0
        while i < len(l) and j < len(r):
            if l[i] <= r[j]: out.append(l[i]); i += 1
            else: out.append(r[j]); j += 1
        return out + l[i:] + r[j:]
    print(merge_sort([5, 2, 4, 7, 1, 3, 2, 6]))
    java
    import java.util.*;
    class Solution {
        static int[] mergeSort(int[] a) {
            if (a.length <= 1) return a;
            int m = a.length / 2;
            int[] l = mergeSort(Arrays.copyOfRange(a, 0, m)), r = mergeSort(Arrays.copyOfRange(a, m, a.length));
            int[] out = new int[a.length];
            int i = 0, j = 0, k = 0;
            while (i < l.length && j < r.length) out[k++] = l[i] <= r[j] ? l[i++] : r[j++];
            while (i < l.length) out[k++] = l[i++];
            while (j < r.length) out[k++] = r[j++];
            return out;
        }
    }
  10. 10

    Sort strings by length, then alphabetically

    easy

    Use a composite sort key (length, string) in Python or a comparator in Java that compares lengths first and then the strings. Complexity: O(n log n) comparisons. Common mistakes: sorting by length only, which leaves ties unordered, and comparing strings with == instead of compareTo in Java.

    python
    def sort_words(w):
        return sorted(w, key=lambda s: (len(s), s))
    print(sort_words(["pear", "fig", "apple", "kiwi", "date"]))  # ['fig', 'date', 'kiwi', 'pear', 'apple']
    java
    import java.util.*;
    class Solution {
        static List<String> sortWords(List<String> w) {
            List<String> out = new ArrayList<>(w);
            out.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
            return out;
        }
    }

Frequently asked questions

What coding topics does Mphasis test?

No published list. Linked lists, trees, recursion and arrays are common in application-development tests.

Should I memorise solutions?

No. Learn the patterns and be able to re-derive them.

Which language is preferred?

Use the one you are strongest in and check the test's allowed languages.

Where do I find real notices?

Use the company's own careers site.

Related guides

More in Company Interview Questions

See all in this section