Morgan Stanley Coding Interview Questions: OA, Technical & Onsite

Morgan Stanley is one of the world's leading financial services firms, with a global technology division that builds mission-critical systems for investment banking, equity trading, wealth management, and risk analytics. Their engineering teams work on ultra-low-latency trading infrastructure, real-time risk engines, and distributed financial data platforms that process billions of dollars in transactions daily.

Whether you're targeting a Technology Analyst (campus hire), Software Engineer, or Intern role, Morgan Stanley's interview process combines rigorous algorithmic problem-solving with finance-flavored system questions. This guide covers the full hiring pipeline, what topics to prioritise, and 50 actual questions reported by candidates.


Morgan Stanley Hiring Process

Morgan Stanley's technology hiring follows a structured multi-stage process:

  1. Application & Resume Screening

    • Apply via Morgan Stanley's careers portal, campus placements, or LinkedIn referrals.
    • Highlight backend systems, distributed computing, or fintech projects. Java and Python are the most common languages; C++ is valued for trading infrastructure roles.
    • Campus Technology Analyst applicants are considered for a rotational program across multiple tech divisions.
  2. Online Assessment — HackerRank / SHL / Codility

    • Shortlisted candidates receive an OA link (typically HackerRank).
    • Format: 90–120 minutes with 3 sections: Aptitude MCQs (20–24 questions, 20 min), Debugging (7–10 questions, 20 min), and 2–3 Coding problems (60 min).
    • Coding problems range from Easy to Medium. Topics: arrays, strings, DP, linked lists, trees, and finance-flavoured problems.
    • Tip: The MCQ section includes output-prediction questions on Java/Python and basic OS/DBMS concepts — don't skip it. The debugging section rewards candidates who can read code critically.
  3. HireVue Video Interview (Behavioural Screening)

    • A pre-recorded video interview with 3–5 behavioural questions.
    • 30 seconds to prepare, ~1.5 minutes to answer each. One retry is allowed per question.
    • Topics: motivation for finance tech, teamwork, handling failure, leadership examples.
    • Tip: Use the STAR format (Situation, Task, Action, Result). Be specific — vague answers score poorly. Mention Morgan Stanley's values: client focus, integrity, and long-term thinking.
  4. Technical Phone Screen / Video Interview

    • A 45–60 minute session on CoderPad or HackerRank with a Morgan Stanley engineer.
    • Expect 1–2 coding problems (Easy to Medium) followed by complexity analysis and edge-case discussion.
    • Topics: linked lists, trees, strings, hash maps, basic DP.
    • Tip: Think aloud. Morgan Stanley interviewers value communication as much as correctness — state your approach before coding and explain tradeoffs.
  5. Onsite / Virtual Technical Rounds (3–4 Rounds)

    • Round 1 — DSA Deep Dive: Core data structures and algorithms. Expect problems requiring optimal solutions — O(n log n) or O(n) where brute force is O(n²).
    • Round 2 — Advanced DSA / Finance Problems: Stock trading variants, matrix DP, priority queues, or system simulation problems. Finance context is often baked into the problem statement.
    • Round 3 — System Design: For experienced hires and senior campus roles — design a real-time fraud detection system, a distributed order book, or a rate limiter for a trading API. Know CAP theorem, caching, and message queues.
    • Round 4 — Behavioural / Hiring Manager: STAR-format questions around ownership, impact, collaboration, and why Morgan Stanley specifically.
    • Tip: For system design, anchor your design to financial constraints — latency budgets (sub-millisecond for trading), consistency requirements (ACID vs eventual), and fault tolerance (99.99% uptime SLAs).
  6. Offer & Onboarding

    • Interviewers submit independent scorecards; a hiring committee makes the final decision.
    • Technology Analyst offers include structured onboarding, mentorship, and cross-division rotation.
    • Campus offers are typically released December–February for August starts.

Preparation Resources

Part 1 — Online Assessment (OA) Questions

These questions appear most frequently in Morgan Stanley's HackerRank / SHL online assessment. The OA tests your ability to deliver correct, efficient solutions under a tight 60-minute coding window.


1. Best Time to Buy and Sell Stock Easy

OAArrays · GreedyLeetCode:#121

Given an array prices where prices[i] is the price of a stock on day i, find the maximum profit from a single buy-sell transaction.

Input:  prices = [7,1,5,3,6,4]
Output: 5  (buy at 1, sell at 6)

Approach: Track the running minimum price. At each day compute profit = price − min_so_far. Track global max.

Complexity: Time O(n) · Space O(1)

Follow-up: What if you can make at most 2 transactions? (LeetCode 123 — use DP with 4 states.)


2. String Subsequence Count Medium

OADynamic Programming · StringsLeetCode:#115

Count the number of distinct ways string t appears as a subsequence in string s.

Input:  s = "rabbbit", t = "rabbit"
Output: 3

Approach: 2-D DP where dp[i][j] = ways to form t[0..j-1] from s[0..i-1]. Transition: if s[i]==t[j], dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; else dp[i-1][j].

Complexity: Time O(m·n) · Space O(m·n), optimisable to O(n) with 1-D DP.

Follow-up: What if t can also include wildcards * and ??


3. Longest Valid Parentheses Medium

OAStack · Dynamic Programming · StringsLeetCode:#32

Given a string of '(' and ')', return the length of the longest valid (well-formed) parentheses substring.

Input:  s = ")()())"
Output: 4  ("()()")

Approach: Use a stack initialised with [-1]. Push index for '('; for ')' pop the top — if stack empty push current index as new base, else length = i - stack.top().

Complexity: Time O(n) · Space O(n)

Follow-up: Solve in O(1) space using two left-right passes counting open/close counters.


4. House Robber Medium

OADynamic Programming · ArraysLeetCode:#198

Given an array of non-negative integers representing money in houses, find the maximum amount you can rob without robbing two adjacent houses.

Input:  nums = [2,7,9,3,1]
Output: 12  (rob 2 + 9 + 1)

Approach: dp[i] = max(dp[i-1], dp[i-2] + nums[i]). Space-optimise to two variables.

Complexity: Time O(n) · Space O(1)

Follow-up: What if the houses are arranged in a circle? (LeetCode 213 — run DP twice, excluding first and last house separately.)


5. Coin Change Medium

OADynamic Programming · BFSLeetCode:#322

Given coin denominations and a target amount, find the minimum number of coins needed to make the amount. Return -1 if impossible.

Input:  coins = [1,5,6,9], amount = 11
Output: 2  (5 + 6)

Approach: Bottom-up DP. dp[0]=0, dp[i] = min(dp[i], dp[i-coin]+1) for each coin ≤ i.

Complexity: Time O(n·amount) · Space O(amount)

Follow-up: Count the total number of ways to make the amount (Coin Change 2 — LeetCode 518).


6. Delete Array Elements (Brick Breaker Variant) Medium

OAStack · Simulation · Arrays

Given an array of integers, repeatedly delete each element that is strictly greater than its left neighbour. Count the total number of deletion operations until no more deletions are possible.

Input:  arr = [5, 3, 4, 2, 6]
Output: 3
Explanation:
  Pass 1: 4 > 3 (delete 4), 6 > 2 (delete 6) → [5,3,2], 2 deletions
  Pass 2: no element > left → stop. Total = 2 initial + 1 from collapse → 3

Approach: Use a stack. Iterate and pop whenever the stack top is less than the current element — each pop counts as one deletion. Push the current element after resolving pops.

Complexity: Time O(n) · Space O(n)

Follow-up: What if we delete elements greater than the right neighbour instead?


Part 2 — Phone Screen & Technical Interview Questions

These questions appear in Morgan Stanley's 45–60 minute phone/video technical screens. Expect 1–2 problems with follow-up questions on complexity, edge cases, and alternative approaches.


7. Valid Parentheses Easy

Phone ScreenStack · StringsLeetCode:#20

Given a string containing just '(', ')', '{', '}', '[', ']', determine if the input string is valid.

Input:  s = "()[]{}"
Output: true

Input:  s = "(]"
Output: false

Approach: Use a stack. Push open brackets; for close brackets check the top of the stack matches. Return true if stack is empty at the end.

Complexity: Time O(n) · Space O(n)

Follow-up: What if the string can also contain letters and we only check bracket structure?


8. LRU Cache Medium

Phone ScreenDesign · HashMap · Doubly Linked ListLeetCode:#146

Design a data structure that follows the Least Recently Used (LRU) cache eviction policy. Implement get(key) and put(key, value) both in O(1).

LRUCache cache = new LRUCache(2);  // capacity 2
cache.put(1, 1);
cache.put(2, 2);
cache.get(1);    // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2);    // returns -1 (not found)

Approach: Combine a HashMap (O(1) lookup) with a doubly linked list (O(1) insert/delete). Head = most recent, tail = least recent. On get/put, move node to head. On capacity exceeded, remove tail.

Complexity: Time O(1) · Space O(capacity)

Follow-up: Implement LFU Cache (LeetCode 460) — evict the least frequently used item.


9. Exchange kth Nodes from Start and End Medium

Phone ScreenLinked List · Two PointersLeetCode:#1721

Given a linked list and an integer k, swap the values of the kth node from the start and the kth node from the end.

Input:  head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Approach: Use two pointers. First reach the kth node from start (save as left). Then advance a second pointer k steps ahead; move both forward until second reaches end — right is now kth from end. Swap values.

Complexity: Time O(n) · Space O(1)

Follow-up: What if you need to swap the actual nodes (not just values)?


10. Next Permutation Medium

Phone ScreenArrays · Two PointersLeetCode:#31

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation. If no next permutation, return the lowest (sorted ascending).

Input:  nums = [4,7,6,5]
Output: [5,4,6,7]

Approach: 1) Find rightmost index i where nums[i] < nums[i+1]. 2) Find rightmost j > i where nums[j] > nums[i]. 3) Swap i and j. 4) Reverse suffix starting at i+1.

Complexity: Time O(n) · Space O(1)

Follow-up: What is the kth permutation of a sequence? (LeetCode 60 — use factorial number system.)


11. Trapping Rain Water Hard

Phone ScreenTwo Pointers · Dynamic Programming · StackLeetCode:&#35;42

Given n non-negative integers representing an elevation map, compute how much water can be trapped after raining.

Input:  height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Approach: Two-pointer. left and right start at ends. Track left_max and right_max. Move the pointer with smaller max: water at that position = max − height. Accumulate.

Complexity: Time O(n) · Space O(1)

Follow-up: 2D version — Trapping Rain Water II (LeetCode 407 — use a min-heap BFS from borders inward).


12. Product of Array Except Self Medium

Phone ScreenArrays · Prefix ProductsLeetCode:&#35;238

Given an integer array nums, return an array output where output[i] is the product of all elements except nums[i]. No division allowed, in O(n) time.

Input:  nums = [1,2,3,4]
Output: [24,12,8,6]

Approach: Two passes. First pass fills result[i] with prefix product (product of all elements to the left). Second pass multiplies from the right using a running right_product variable.

Complexity: Time O(n) · Space O(1) (excluding output array)

Follow-up: How would you handle zeroes in the array? (Count zeros: if >1 all results are 0; if exactly 1 only the zero-position result is non-zero.)


13. Spiral Matrix Medium

Phone ScreenMatrix · SimulationLeetCode:&#35;54

Given an m × n matrix, return all elements in spiral order (clockwise from top-left).

Input:  [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]

Approach: Maintain four boundaries: top, bottom, left, right. Traverse right, down, left, up. Shrink boundaries after each direction. Stop when boundaries cross.

Complexity: Time O(m·n) · Space O(1) (excluding output)

Follow-up: Spiral Matrix II — fill numbers 1 to n² into a matrix in spiral order (LeetCode 59).


Part 3 — Onsite Technical & Finance-Flavoured Questions

These questions appear in Morgan Stanley's deeper onsite/virtual rounds. Expect harder DSA, finance-themed simulations, system design components, and sustained discussion of complexity and tradeoffs.


14. Maximum Subarray (Kadane's) Easy

OnsiteDynamic Programming · ArraysLeetCode:&#35;53

Find the contiguous subarray with the largest sum and return its sum.

Input:  nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6  (subarray [4,-1,2,1])

Approach: Kadane's — maintain current_sum. At each element: current_sum = max(num, current_sum + num). Track global max. Reset when current_sum goes negative.

Complexity: Time O(n) · Space O(1)

Follow-up: Return the actual subarray indices, not just the sum. (Track start and end indices when updating max.)


15. Intersection of Two Linked Lists Easy

OnsiteLinked List · Two PointersLeetCode:&#35;160

Given two singly linked list heads, return the node at which they intersect, or null if they don't.

A: a1 → a2 ↘
              c1 → c2 → c3
B: b1 → b2 → b3 ↗

Output: c1

Approach: Two pointers. Each traverses both lists (A then B, B then A). They meet at the intersection node after equal total distances, or both become null simultaneously.

Complexity: Time O(m+n) · Space O(1)

Follow-up: How would you detect if a single linked list has a cycle? (Floyd's slow/fast pointer — LeetCode 141.)


16. Min Stack Medium

OnsiteStack · DesignLeetCode:&#35;155

Design a stack that supports push, pop, top, and retrieving the minimum element — all in O(1).

MinStack s;
s.push(-2); s.push(0); s.push(-3);
s.getMin(); // -3
s.pop();
s.top();    // 0
s.getMin(); // -2

Approach: Maintain two stacks — the main stack and an auxiliary min-stack. On push, push to main; push to min-stack only if value ≤ current min. On pop, if popped value equals min-stack top, also pop min-stack.

Complexity: Time O(1) · Space O(n)

Follow-up: Implement a Max Stack with O(1) getMax and O(log n) pop (LeetCode 716 — use a sorted structure alongside the stack).


17. Valid Anagram Easy

OnsiteHashMap · Sorting · StringsLeetCode:&#35;242

Given two strings s and t, return true if they are anagrams of each other.

Input:  s = "anagram", t = "nagaram"
Output: true

Approach: Count character frequencies with a 26-element array. Increment for s, decrement for t. If all zeros at the end, they're anagrams.

Complexity: Time O(n) · Space O(1) (fixed 26-char alphabet)

Follow-up: Group anagrams together (LeetCode 49 — use sorted string as HashMap key).


18. Boolean Matrix (Set Rows and Columns to Zero) Medium

OnsiteMatrix · In-placeLeetCode:&#35;73

Given an m×n matrix, if an element is 0, set its entire row and column to 0 in-place.

Input:  [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Approach: Use the first row and first column as markers. Two special flags track whether first row/column themselves contain zeros. Two passes: first mark, then zero out.

Complexity: Time O(m·n) · Space O(1)

Follow-up: What if you can use O(m+n) extra space? (Simply store which rows/cols need zeroing in separate arrays.)


19. Find Minimum in Rotated Sorted Array Medium

OnsiteBinary Search · ArraysLeetCode:&#35;153

Given a sorted array rotated between 1 and n times, find the minimum element in O(log n).

Input:  nums = [3,4,5,1,2]
Output: 1

Approach: Binary search. If nums[mid] > nums[right], minimum is in the right half. Otherwise it's in the left half (including mid).

Complexity: Time O(log n) · Space O(1)

Follow-up: What if duplicates are allowed? (Worst case O(n) — when nums[mid] == nums[right] shrink right by 1.)


20. Letter Combinations of a Phone Number Medium

OnsiteBacktracking · RecursionLeetCode:&#35;17

Given a string of digits (2–9), return all possible letter combinations that the number could represent (phone keypad mapping).

Input:  digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Approach: Backtracking. Maintain a digit-to-letters map. Recurse on each position: for each letter mapped to the current digit, append and recurse to next digit. Base case: current string length equals digits length.

Complexity: Time O(4^n · n) · Space O(n) recursion depth

Follow-up: How does this change if digits can include 0 and 1 (which have no letters)? (Skip those digits in the recursion.)


21. Palindromic Substrings Medium

OnsiteDynamic Programming · Expand Around CentreLeetCode:&#35;647

Count the number of palindromic substrings in a given string.

Input:  s = "aaa"
Output: 6  ("a","a","a","aa","aa","aaa")

Approach: Expand around centre. For each index try both odd (single centre) and even (double centre) expansions. Count each valid palindrome.

Complexity: Time O(n²) · Space O(1)

Follow-up: Find the longest palindromic substring (LeetCode 5 — same expand-around-centre, track max length and start index).


22. Climbing Stairs (Count Ways) Easy

OnsiteDynamic ProgrammingLeetCode:&#35;70

You are climbing a staircase with n steps. Each time you can climb 1 or 2 steps. Count the number of distinct ways to reach the top.

Input:  n = 5
Output: 8

Approach: Fibonacci recurrence. dp[i] = dp[i-1] + dp[i-2]. Space-optimise to two variables.

Complexity: Time O(n) · Space O(1)

Follow-up: What if you can jump 1, 2, or 3 steps? (Tribonacci recurrence — same approach with three variables.)


23. Jump Game Medium

OnsiteGreedy · Dynamic ProgrammingLeetCode:&#35;55

Given an integer array where nums[i] is your max jump length at position i, determine if you can reach the last index.

Input:  nums = [2,3,1,1,4]
Output: true

Input:  nums = [3,2,1,0,4]
Output: false

Approach: Greedy. Track the furthest reachable index. If current index exceeds it, return false. Update max_reach = max(max_reach, i + nums[i]).

Complexity: Time O(n) · Space O(1)

Follow-up: Minimum number of jumps to reach the last index (LeetCode 45 — greedy BFS layer approach).


24. Subsets Medium

OnsiteBacktracking · Bit ManipulationLeetCode:&#35;78

Given an integer array with unique elements, return all possible subsets (the power set).

Input:  nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

Approach: Backtracking — at each index either include or exclude the element. Alternatively, iterate over all 2^n bitmasks and include element i if bit i is set.

Complexity: Time O(n · 2^n) · Space O(n) recursion depth

Follow-up: Subsets II with duplicates (LeetCode 90 — sort first, skip duplicates at the same recursion level).


25. Merge Intervals Medium

OnsiteSorting · IntervalsLeetCode:&#35;56

Given an array of intervals, merge all overlapping intervals and return the result.

Input:  intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Approach: Sort by start time. Iterate and merge if current start ≤ previous end (update end to max of both ends). Otherwise start a new interval.

Complexity: Time O(n log n) · Space O(n)

Follow-up: Insert a new interval into a sorted list of non-overlapping intervals (LeetCode 57 — single pass with three phases: before, during, after the new interval).


26. Word Search Medium

OnsiteDFS · Backtracking · MatrixLeetCode:&#35;79

Given an m×n grid of characters and a word, return true if the word exists in the grid (horizontally or vertically adjacent cells, each used once).

Input:  board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Approach: DFS backtracking from every cell. Mark visited by temporarily replacing with a sentinel. Restore on backtrack.

Complexity: Time O(m·n·4^L) where L is word length · Space O(L) recursion depth

Follow-up: Word Search II — find all words from a dictionary in the grid (LeetCode 212 — use Trie for pruning).


27. Pow(x, n) Medium

OnsiteMath · Recursion · Divide and ConquerLeetCode:&#35;50

Implement pow(x, n), which calculates x raised to the power n, including negative n.

Input:  x = 2.0, n = -2
Output: 0.25  (1/4)

Approach: Fast exponentiation. If n is even: pow(x, n) = pow(x*x, n/2). If odd: x * pow(x, n-1). For negative n: pow(1/x, -n).

Complexity: Time O(log n) · Space O(log n) recursion (O(1) iterative)

Follow-up: How do you handle integer overflow when n = INT_MIN? (Convert n to long before negating.)


28. Largest Rectangle in Histogram Hard

OnsiteStack · ArraysLeetCode:&#35;84

Given an array of bar heights in a histogram, find the largest rectangle that can be formed.

Input:  heights = [2,1,5,6,2,3]
Output: 10  (bars of height 5 and 6, width 2)

Approach: Monotonic increasing stack. For each bar, pop all taller bars when a shorter bar is encountered. The width for the popped bar extends from its new stack top to the current index.

Complexity: Time O(n) · Space O(n)

Follow-up: Maximal Rectangle in a binary matrix (LeetCode 85 — apply histogram solution row by row).


29. Unique Paths Medium

OnsiteDynamic Programming · MathLeetCode:&#35;62

A robot on an m×n grid starts at the top-left and wants to reach the bottom-right. It can only move right or down. Count distinct paths.

Input:  m = 3, n = 7
Output: 28

Approach: dp[i][j] = dp[i-1][j] + dp[i][j-1]. Space-optimise to a single row.

Complexity: Time O(m·n) · Space O(n)

Follow-up: Unique Paths II — some cells are obstacles (LeetCode 63 — set blocked cells to 0 in DP).


30. Longest Common Subsequence Medium

OnsiteDynamic Programming · StringsLeetCode:&#35;1143

Given two strings, return the length of their longest common subsequence.

Input:  text1 = "abcde", text2 = "ace"
Output: 3  ("ace")

Approach: 2-D DP. If s1[i] == s2[j]: dp[i][j] = dp[i-1][j-1] + 1. Else: max(dp[i-1][j], dp[i][j-1]).

Complexity: Time O(m·n) · Space O(m·n), optimisable to O(min(m,n)).

Follow-up: Shortest Common Supersequence (LeetCode 1092 — LCS + total lengths minus LCS length).


31. Word Break Medium

OnsiteDynamic Programming · TrieLeetCode:&#35;139

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a sequence of one or more dictionary words.

Input:  s = "leetcode", wordDict = ["leet","code"]
Output: true

Approach: DP. dp[i] = true if s[0..i-1] can be segmented. For each i, check all j < i: if dp[j] and s[j..i-1] is in the dictionary, dp[i] = true.

Complexity: Time O(n²) · Space O(n)

Follow-up: Return all ways to segment the string (LeetCode 140 — backtracking with memoization).


32. Kth Largest Element in an Array Medium

OnsiteHeap · QuickselectLeetCode:&#35;215

Find the kth largest element in an unsorted array (not necessarily distinct).

Input:  nums = [3,2,1,5,6,4], k = 2
Output: 5

Approach: Min-heap of size k. Push each element; if heap size > k, pop the smallest. Final heap top is the kth largest. Alternatively, quickselect achieves O(n) average.

Complexity: Heap: Time O(n log k) · Space O(k). Quickselect: Time O(n) avg · Space O(1).

Follow-up: Find the kth smallest element in a sorted matrix (LeetCode 378 — binary search on value range with count function).


33. Longest Increasing Subsequence Medium

OnsiteDynamic Programming · Binary SearchLeetCode:&#35;300

Find the length of the longest strictly increasing subsequence in an integer array.

Input:  nums = [10,9,2,5,3,7,101,18]
Output: 4  ([2,3,7,101])

Approach (O(n log n)): Maintain a tails array. For each element, binary search for its position in tails and update. Length of tails = LIS length.

Complexity: Time O(n log n) · Space O(n)

Follow-up: Russian Doll Envelopes (LeetCode 354 — sort by width ascending, height descending, then LIS on heights).


34. First Missing Positive Hard

OnsiteArrays · Index HashingLeetCode:&#35;41

Given an unsorted integer array, find the smallest missing positive integer in O(n) time and O(1) extra space.

Input:  nums = [3,4,-1,1]
Output: 2

Approach: Use the array itself as a hash. For every value v in range [1,n], place it at index v-1 by swapping. Then scan: the first index where nums[i] != i+1 gives the answer.

Complexity: Time O(n) · Space O(1)

Follow-up: Find all missing numbers in [1, n] (LeetCode 448 — same index-negation trick, collect indices with positive values).


35. Binary Tree Level Order Traversal Medium

OnsiteBFS · TreesLeetCode:&#35;102

Given the root of a binary tree, return the level order traversal of its node values (left to right, level by level).

Input:  root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Approach: BFS with a queue. For each level, record the queue size, dequeue exactly that many nodes, collect their values, enqueue their children.

Complexity: Time O(n) · Space O(n)

Follow-up: Zigzag level order traversal (LeetCode 103 — alternate appending direction using a flag).


36. Mirror / Invert Binary Tree Easy

OnsiteTrees · DFS · RecursionLeetCode:&#35;226

Invert (mirror) a binary tree by swapping left and right children at every node.

Input:  [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Approach: Recursive post-order. Swap left and right children, then recurse into each.

Complexity: Time O(n) · Space O(h) (h = height)

Follow-up: Check if two trees are mirror images of each other (LeetCode 101 Symmetric Tree — compare left-right and right-left simultaneously with two pointers).


37. Number of Islands Medium

OnsiteDFS · BFS · Union-Find · MatrixLeetCode:&#35;200

Given an m×n binary grid of '1's (land) and '0's (water), return the number of islands.

Input:  [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
Output: 3

Approach: DFS/BFS from each unvisited '1', marking visited cells as '0'. Each DFS call = one island. Alternatively use Union-Find.

Complexity: Time O(m·n) · Space O(m·n)

Follow-up: Maximum area of island (LeetCode 695 — return max DFS component size instead of count).


38. Implement atoi() Medium

OnsiteStrings · Edge CasesLeetCode:&#35;8

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.

Input:  s = "   -42abc"
Output: -42

Input:  s = "2147483648"
Output: 2147483647  (INT_MAX clamp)

Approach: Strip leading whitespace → read optional sign → read digits → clamp to [INT_MIN, INT_MAX]. Overflow check before multiplying by 10: if result > (INT_MAX - digit) / 10, clamp.

Complexity: Time O(n) · Space O(1)

Follow-up: What state machine (DFA) can model this parsing? (3 states: start, signed, in_number.)


39. Best Time to Buy and Sell Stock III (At Most 2 Transactions) Hard

OnsiteDynamic Programming · FinanceLeetCode:&#35;123

Given stock prices, find the maximum profit using at most 2 transactions (you must sell before buying again).

Input:  prices = [3,3,5,0,0,3,1,4]
Output: 6  (buy at 0 sell at 3, buy at 1 sell at 4)

Approach: Track 4 states: buy1, sell1, buy2, sell2. Update in order each day. buy1 = max(buy1, -price), sell1 = max(sell1, buy1+price), buy2 = max(buy2, sell1-price), sell2 = max(sell2, buy2+price).

Complexity: Time O(n) · Space O(1)

Follow-up: At most k transactions (LeetCode 188 — generalise to k buy/sell state pairs).


40. Rate Limiter Design (Token Bucket / Sliding Window) Hard

OnsiteSystem Design · Queue · Finance

Design a rate limiter for a trading API that allows at most N requests per second per user. Handle concurrent requests efficiently.

Design:
  Token Bucket: capacity N, refill 1 token/ms
  On request: if tokens > 0, decrement and allow; else reject

  Sliding Window Counter: store timestamps in a queue
  On request: evict timestamps older than 1s; if queue.size() < N, allow and push timestamp

Approach — Sliding Window Log: Use a queue of timestamps per user. On each request, remove entries older than the window. If queue size < N, allow. Otherwise reject. For distributed systems, use Redis ZSET with TTL.

Complexity: Time O(N) per request (eviction) · Space O(N) per user

Follow-up: How do you implement this across 100 distributed nodes without a central store? (Gossip protocol + approximate counters like HyperLogLog.)


41. Search Suggestions System Medium

OnsiteTrie · Binary Search · StringsLeetCode:&#35;1268

Given a list of products and a search word, return a list of up to 3 suggested products after each character is typed, sorted lexicographically.

Input:  products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
Output: [["mobile","moneypot","monitor"],["mobile","moneypot","monitor"],["mouse","mousepad"],["mouse","mousepad"],["mouse","mousepad"]]

Approach: Sort products. For each prefix, binary search for the insertion point and collect up to 3 words starting with that prefix. Alternatively, build a Trie with sorted word lists at each node.

Complexity: Time O(n·log n + m·log n) · Space O(n·L)

Follow-up: How would you build this for a live autocomplete system serving millions of users? (Trie in memory with LRU caching of hot prefixes, backed by a distributed key-value store.)


42. Reverse Words in a String Medium

OnsiteStrings · Two PointersLeetCode:&#35;151

Given a string s, reverse the order of words (removing leading/trailing spaces and reducing multiple spaces to one).

Input:  s = "  the sky  is blue  "
Output: "blue is sky the"

Approach: Split by spaces (filter empty tokens), reverse the list, join with single space. In-place approach: reverse entire string, then reverse each word, then clean spaces.

Complexity: Time O(n) · Space O(n)

Follow-up: Rotate a string — check if one string is a rotation of another (LeetCode 796 — check if s2 is a substring of s1+s1).


43. Maximum Product Subarray Medium

OnsiteDynamic Programming · ArraysLeetCode:&#35;152

Find the contiguous subarray with the largest product.

Input:  nums = [2,3,-2,4]
Output: 6  ([2,3])

Approach: Track both max and min products at each step (negative × negative = positive). max_p = max(num, max_p*num, min_p*num). Track global max.

Complexity: Time O(n) · Space O(1)

Follow-up: What if the array contains zeros? (Zeros split the problem — reset both trackers at each zero.)


44. Detect Cycle in Directed Graph Medium

OnsiteGraphs · DFS · Topological SortLeetCode:&#35;207

Given a directed graph (as list of prerequisites), determine if it's possible to finish all courses (i.e., the graph has no cycle).

Input:  numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false  (cycle: 0→1→0)

Approach: DFS with 3-colour marking: white (unvisited), grey (in-progress), black (done). If DFS reaches a grey node, a cycle exists. Alternatively, Kahn's algorithm (BFS topological sort) — if the processed count < numCourses, a cycle exists.

Complexity: Time O(V+E) · Space O(V)

Follow-up: Return the actual course order if possible (LeetCode 210 — topological sort with Kahn's BFS).


45. Minimum Window Substring Hard

OnsiteSliding Window · HashMapLeetCode:&#35;76

Given strings s and t, return the minimum window in s that contains all characters of t (including duplicates). Return "" if impossible.

Input:  s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

Approach: Sliding window with two frequency maps. Expand right until window is valid (contains all of t). Contract left while still valid — track minimum length window.

Complexity: Time O(|s| + |t|) · Space O(|t|)

Follow-up: Minimum window subsequence (LeetCode 727 — characters must appear in order, not just present).


46. Largest Sum Subarray (Maximum Sum Increasing Subsequence) Medium

OnsiteDynamic Programming · Arrays

Find the sum of the maximum sum increasing subsequence of a given array — a subsequence that is strictly increasing and has the maximum possible sum.

Input:  arr = [1, 101, 2, 3, 100, 4, 5]
Output: 106  (1 + 2 + 3 + 100)

Approach: DP similar to LIS. dp[i] = max sum of increasing subsequence ending at index i. For each i, check all j < i where arr[j] < arr[i]: dp[i] = max(dp[i], dp[j] + arr[i]). Answer is max of all dp[i].

Complexity: Time O(n²) · Space O(n)

Follow-up: Can you optimise to O(n log n) using a segment tree indexed by value?


47. Stock Price Maximisation (10-Minute Intervals) Medium

OnsiteGreedy · Finance · Arrays

You have stock prices recorded at 10-minute intervals throughout a trading day. You can make at most one buy and one sell. Your broker requires at least 30 minutes between buy and sell (you can't sell within 3 intervals of buying). Find the maximum profit.

Input:  prices = [100, 90, 110, 80, 140, 70, 120]  (each 10 min apart)
Output: 60  (buy at 80 [index 3], sell at 140 [index 4] → gap = 1 interval = 10 min,
             but need ≥ 3 intervals → buy at 90 [index 1], sell at 140 [index 4] = 50)

Approach: Precompute suffix maximum prices. For each buy day i, the earliest valid sell day is i + 3. Max profit = max over all i of suffix_max[i+3] - prices[i].

Complexity: Time O(n) · Space O(n)

Follow-up: How does the solution change if you can make unlimited transactions with the 30-minute constraint?


48. Flatten Binary Tree to Linked List Medium

OnsiteTrees · Linked List · Morris TraversalLeetCode:&#35;114

Given the root of a binary tree, flatten it to a linked list in-place using pre-order traversal order.

Input:  [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]

Approach: Reverse post-order (right, left, root). Maintain a prev pointer. Set node.right = prev, node.left = null, update prev = node.

Complexity: Time O(n) · Space O(h) (h = height)

Follow-up: Can you do this O(1) space? (Morris traversal — for each node with a left subtree, find the rightmost node of the left subtree and rewire.)


49. Sort Colors (Dutch National Flag) Medium

OnsiteThree Pointers · SortingLeetCode:&#35;75

Given an array with only values 0, 1, 2 (representing colours red, white, blue), sort them in-place so that all 0s come first, then 1s, then 2s — one pass, O(1) space.

Input:  nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Approach: Dutch National Flag (3-way partition). Pointers low=0, mid=0, high=n-1. If nums[mid]==0: swap with low, advance both. If 1: advance mid. If 2: swap with high, decrement high.

Complexity: Time O(n) · Space O(1)

Follow-up: 4-way partition for values 0–3 — extend to two additional boundary pointers.


50. Real-Time Fraud Detection System Design Hard

OnsiteSystem Design · Finance · Streaming

Design a real-time fraud detection system for a banking platform. The system receives millions of financial transactions per second and must flag suspicious ones in under 100ms.

Components:
  Ingestion: Kafka topics partitioned by user_id
  Feature Store: Redis (latest user features — avg spend, location, device)
  Rule Engine: fast path — threshold checks (amount > 10x avg → flag)
  ML Scoring: model inference service (sub-50ms latency)
  Alert Store: Cassandra (high write throughput, time-series access)
  Feedback Loop: labelled fraud feeds back to retrain models nightly

Approach: Two-tier architecture. Tier 1: deterministic rule engine (< 5ms) rejects obvious fraud. Tier 2: ML scoring for borderline cases (< 100ms). Partition Kafka by user_id so per-user state is always on the same consumer. Use Redis for sub-millisecond feature lookups.

Key Design Decisions: Kafka for durability and replay. Redis for hot feature cache. Cassandra for write-heavy alert storage. Separate read and write paths (CQRS).

Follow-up: How do you handle false positives that block legitimate high-value transactions? (Human review queue with SLA, customer notification, manual override API.)


Morgan Stanley Interview Preparation Tips

  • Finance context matters: Morgan Stanley interviewers often embed stock trading, portfolio, or transaction-processing scenarios into otherwise standard DSA questions. Practise framing solutions in financial terms — "this would represent the order book" or "this latency constraint maps to sub-tick trading."
  • HireVue is eliminatory: Many candidates underestimate the HireVue round. Record practice answers on your phone and review them. A vague or rambling answer to "Why Morgan Stanley?" costs you the next round.
  • OA debugging section: This is unique to Morgan Stanley among major firms. Practise reading buggy Java/Python code under time pressure — common bugs are off-by-one errors, wrong loop conditions, missing null checks, and incorrect base cases.
  • Explain before coding: Morgan Stanley interviews rate communication highly. Always state your approach, complexity, and edge cases before writing a single line of code.
  • Focus on DP and stock variants: Best Time to Buy and Sell Stock I/II/III, Coin Change, House Robber, LCS, and Distinct Subsequences are disproportionately common. Master all variants.
  • System design for senior roles: For experienced or final-round interviews, prepare designs for a fraud detection pipeline, a distributed order book, and a real-time risk calculation engine. Know CAP theorem, consistent hashing, and message queue semantics.