Morgan Stanley coding round questions with solutions
Last updated 2026-11-19
Morgan Stanley technology assessments are commonly described as a mix of coding problems and technical MCQs, with linked lists, trees, dynamic programming and string problems at medium difficulty. This set is practice in that style: nine coding problems and two MCQs, each with a worked solution.
None of these is a recalled question. After the test, see Morgan Stanley interview questions for the interviews.
| Style | Medium linked list, tree, DP, string and SQL problems |
|---|---|
| Languages here | Python, Java, SQL |
| Problems | 9 coding, 2 MCQ-style |
| Level | Easy to hard |
How to approach this set
Pointer and recursion problems are where partial scores are lost: draw the structure before coding, and trace a three-node example. For tree problems, decide whether recursion or a queue is cleaner before you start, and state the space cost of the recursion stack.
Time yourself at 25 minutes per medium problem. Review timing and platform behaviour in how to crack an online assessment, and use how to crack a technical MCQ test for the objective questions.
Morgan Stanley coding round questions with solutions: questions with worked answers
1 Reverse a linked list in groups of k; leave a final group shorter than k as it is.
hardFirst check that k nodes remain; if not, stop. Reverse those k nodes with the usual three-pointer loop, then connect the previous group's tail to the new head and recurse or loop on the rest. Time O(n), space O(1) iteratively (O(n/k) recursion if recursive). The frequent mistakes are reversing the incomplete tail group, and losing the link between groups.
pythonclass Node: def __init__(self, v, nxt=None): self.val, self.next = v, nxt def reverse_k(head, k): probe = head for _ in range(k): if not probe: return head probe = probe.next prev, cur = reverse_k(probe, k), head for _ in range(k): cur.next, prev, cur = prev, cur, cur.next return prevjavaclass Solution { static class Node { int val; Node next; Node(int v) { val = v; } } static Node reverseK(Node head, int k) { Node probe = head; for (int i = 0; i < k; i++) { if (probe == null) return head; probe = probe.next; } Node prev = reverseK(probe, k), cur = head; for (int i = 0; i < k; i++) { Node nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; } return prev; } }2 Binary tree level order traversal.
easyUse a queue. For each level, record the current queue size, pop exactly that many nodes, collect their values and push their children. Time O(n), space O(w) where w is the maximum width. The mistake is not fixing the level size before the inner loop, which mixes levels because the queue grows as you go.
pythonfrom collections import deque def level_order(root): out, q = [], deque([root] if root else []) while q: out.append([]) for _ in range(len(q)): n = q.popleft() out[-1].append(n.val) if n.left: q.append(n.left) if n.right: q.append(n.right) return outjavaimport java.util.*; class Solution { static class TreeNode { int val; TreeNode left, right; } static List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> out = new ArrayList<>(); if (root == null) return out; Queue<TreeNode> q = new ArrayDeque<>(); q.add(root); while (!q.isEmpty()) { List<Integer> level = new ArrayList<>(); for (int i = q.size(); i > 0; i--) { TreeNode n = q.poll(); level.add(n.val); if (n.left != null) q.add(n.left); if (n.right != null) q.add(n.right); } out.add(level); } return out; } }3 Lowest common ancestor of two nodes in a binary tree.
mediumRecurse: if the current node is null or equals p or q, return it. Recurse into both children; if both return non-null, the current node is the LCA, otherwise return whichever side is non-null. Time O(n), space O(h). It assumes both nodes exist in the tree. For a BST you can instead walk down comparing values in O(h), which is the follow-up interviewers like to ask.
pythondef lca(root, p, q): if root is None 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)javaclass Solution { static class TreeNode { int val; TreeNode left, right; } static 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 Coin change: the fewest coins needed to make an amount, or -1 if impossible.
mediumBottom-up DP: dp[a] is the minimum coins for amount a, with dp[0] = 0 and every other entry starting at infinity. For each amount, try each coin c <= a and take dp[a - c] + 1. Time O(amount x coins), space O(amount). The greedy 'largest coin first' fails for coins like {1, 3, 4} and amount 6 (greedy gives 4+1+1, the optimum is 3+3). Do not initialise with 0, which makes impossible amounts look free.
pythondef coin_change(coins, amount): INF = amount + 1 dp = [0] + [INF] * amount for a in range(1, amount + 1): for c in coins: if c <= a: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != INF else -1javaimport java.util.*; class Solution { static int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, amount + 1); dp[0] = 0; for (int a = 1; a <= amount; a++) for (int c : coins) if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1); return dp[amount] > amount ? -1 : dp[amount]; } }5 Longest palindromic substring.
mediumExpand around each centre. There are 2n - 1 centres (each character and each gap between characters); expand outwards while the ends match and record the longest span. Time O(n^2), space O(1). Dynamic programming is also O(n^2) but uses O(n^2) space, and Manacher's algorithm gives O(n). The common mistake is handling only odd-length palindromes.
pythondef longest_pal(s): best = (0, 0) for c in range(len(s)): for l, r in ((c, c), (c, c + 1)): while l >= 0 and r < len(s) and s[l] == s[r]: l -= 1; r += 1 if r - l - 1 > best[1] - best[0]: best = (l + 1, r) return s[best[0]:best[1]]javaclass Solution { static String longestPal(String s) { int start = 0, end = 0; for (int c = 0; c < s.length(); c++) { for (int k = 0; k < 2; k++) { int l = c, r = c + k; while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { l--; r++; } if (r - l - 1 > end - start) { start = l + 1; end = r; } } } return s.substring(start, end); } }6 3Sum: find all unique triplets that sum to zero.
mediumSort, then fix the first element and use two pointers on the rest. Skip duplicate values for the fixed element and, after a hit, for both pointers. Time O(n^2), space O(1) beyond the output and the sort. Mistakes: returning duplicate triplets and forgetting to move both pointers after finding a match, which loops forever.
pythondef three_sum(a): a.sort() out = [] for i in range(len(a) - 2): if i and a[i] == a[i - 1]: continue l, r = i + 1, len(a) - 1 while l < r: s = a[i] + a[l] + a[r] if s < 0: l += 1 elif s > 0: r -= 1 else: out.append([a[i], a[l], a[r]]) l += 1; r -= 1 while l < r and a[l] == a[l - 1]: l += 1 return outjavaimport java.util.*; class Solution { static List<List<Integer>> threeSum(int[] a) { Arrays.sort(a); List<List<Integer>> out = new ArrayList<>(); for (int i = 0; i < a.length - 2; i++) { if (i > 0 && a[i] == a[i - 1]) continue; int l = i + 1, r = a.length - 1; while (l < r) { int s = a[i] + a[l] + a[r]; if (s < 0) l++; else if (s > 0) r--; else { out.add(Arrays.asList(a[i], a[l], a[r])); l++; r--; while (l < r && a[l] == a[l - 1]) l++; } } } return out; } }7 Count subarrays whose sum equals k (the array may contain negatives).
mediumUse prefix sums with a hash map of how many times each prefix sum has occurred. At each index, the number of subarrays ending here with sum k equals the count of earlier prefixes equal to current - k. Seed the map with {0: 1} for subarrays starting at index 0. Time O(n), space O(n). A sliding window fails here because negative numbers break the monotonic property.
pythonfrom collections import defaultdict def subarray_sum(a, k): seen, s, cnt = defaultdict(int), 0, 0 seen[0] = 1 for x in a: s += x cnt += seen[s - k] seen[s] += 1 return cntjavaimport java.util.*; class Solution { static int subarraySum(int[] a, int k) { Map<Integer, Integer> seen = new HashMap<>(); seen.put(0, 1); int s = 0, cnt = 0; for (int x : a) { s += x; cnt += seen.getOrDefault(s - k, 0); seen.merge(s, 1, Integer::sum); } return cnt; } }8 Rotate an n x n matrix 90 degrees clockwise in place.
mediumTranspose the matrix (swap a[i][j] with a[j][i] for j > i), then reverse each row. Time O(n^2), space O(1). Swapping across the whole matrix during the transpose undoes the work, so loop j from i + 1. For anticlockwise, reverse rows first or transpose along the other diagonal.
pythondef 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()javaclass Solution { static 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 l = 0, r = n - 1; l < r; l++, r--) { int t = row[l]; row[l] = row[r]; row[r] = t; } } }9 SQL: find customers who have never placed an order.
easyLEFT JOIN customers to orders and keep rows where the order side is NULL, or use NOT EXISTS. Avoid NOT IN on a column that can contain NULLs: one NULL makes the whole predicate unknown and returns no rows. NOT EXISTS is the safest form and usually optimises well.
sqlSELECT c.id, c.name FROM Customers c WHERE NOT EXISTS (SELECT 1 FROM Orders o WHERE o.customer_id = c.id);10 MCQ: what is the maximum number of nodes in a binary tree of height h, where a single node has height 0?
easyEach level i holds at most 2^i nodes, so the total is 1 + 2 + 4 + ... + 2^h = 2^(h+1) - 1. If the question counts height in levels instead, a single node has height 1 and the answer is 2^h - 1. Read the definition in the question stem; this off-by-one is the whole trick in such MCQs.
11 MCQ: two fair dice are rolled. What is the probability that the sum is 9?
easyThe pairs that sum to 9 are (3,6), (4,5), (5,4) and (6,3): four outcomes out of 36, so the probability is 4/36 = 1/9. Counting (4,5) and (5,4) as one outcome is the usual slip, since dice are distinguishable. For sums, list pairs by the smaller die and double the non-equal ones.
Frequently asked questions
What topics matter most for the Morgan Stanley coding round?
Linked lists, trees, arrays, strings and dynamic programming are the commonly reported areas, with some SQL and CS MCQs.
Is the test proctored?
Formats vary by cycle, so read your invitation for proctoring rules and allowed tools.
How should I split my time?
Spend a few minutes reading all problems, solve the easiest first, and leave time to test edge cases on each.
Are these the real questions?
No. They are original practice problems in the style of the topics the round commonly covers.
Related guides
- Morgan Stanley interview questions with answers (technology analyst)
- Goldman Sachs coding round questions with solutions
- JPMorgan coding round questions with solutions
- Dynamic Programming Interview Questions
- Linked list interview questions with worked solutions
- Binary Tree Interview Questions and Answers
More in Company Interview Questions
- Morgan Stanley interview questions with answers (technology analyst)
- Mphasis Coding Round Questions with Solutions
- Mphasis Interview Questions for Freshers
- Mu Sigma Coding and Analytical Round Questions
- Mu Sigma Interview Questions with Answers
- Myntra Coding Round Questions with Solutions
- Myntra Interview Questions and Answers
- Nagarro coding round questions
- Nagarro interview questions and answers
- Netflix Coding Round Questions with Solutions in Python and Java
- Netflix Interview Questions and Answers for Engineers
- NTT DATA coding round questions