JP Morgan Chase Online Assessment & SDE Interview Questions
JP Morgan Chase & Co. is one of the world's largest financial institutions, employing over 50,000 technologists globally. Its technology division — JPMorgan Chase Tech — builds mission-critical systems for investment banking, asset management, trading platforms, cybersecurity, and digital payments. Engineers at JP Morgan work on high-throughput, low-latency systems that process millions of transactions daily, making performance and correctness non-negotiable.
Whether you are applying for a Software Engineer, Technology Analyst (campus), Associate SDE, or Quantitative Developer role, their interview process is rigorous and tests both your algorithmic depth and your ability to reason about real-world system constraints. This guide walks you through everything — the hiring stages, what to prepare, tips from past interviews, and a curated set of commonly asked coding questions.
Understanding JP Morgan's Hiring Process
JP Morgan Chase's hiring process for technology roles typically follows these stages:
Application Submission:
- Apply via JP Morgan's official careers portal (jpmorgan.com/careers), campus placements, LinkedIn, or employee referrals.
- Highlight projects involving backend systems, distributed systems, databases, or anything in the fintech/finance domain. Java, Python, and C++ are the most commonly expected languages.
- Campus applicants are typically considered for the Technology Analyst program, which rotates you across multiple technology teams.
Online Coding Assessment (HackerRank / Codility):
- Shortlisted candidates receive an online assessment link, usually via HackerRank or Codility.
- Duration: 60–90 minutes with 2–3 coding problems of varying difficulty (Easy to Hard).
- Topics: arrays, strings, hash maps, recursion, dynamic programming, graphs, and occasionally SQL or probability-based reasoning.
- Some roles include an additional MCQ section on data structures, OS concepts, or DBMS.
- Tip: Read constraints carefully — JP Morgan OA problems often have tight time limits that reward O(n log n) or better solutions.
Technical Phone / Video Interview:
- A 45–60 minute round with a JP Morgan software engineer on a shared coding platform (CoderPad or similar).
- Expect 1–2 problems, followed by discussion on complexity, edge cases, and alternative approaches.
- You may be asked to trace through your code with a specific input — practice narrating your logic as you code.
Virtual / On-Site Interview Rounds (3–4 rounds):
- Round 1 — Data Structures & Algorithms: Core DSA problems. Emphasis on correctness, clean code, and optimal complexity.
- Round 2 — System Design: Design a scalable financial system such as a real-time fraud detection pipeline, a rate limiter for trading APIs, or a distributed transaction ledger. Common for experienced hires; occasionally asked for campus roles at the final stage.
- Round 3 — Behavioral / Leadership: Structured competency questions aligned with JP Morgan's values — ownership, client focus, integrity, and teamwork. Use the STAR format (Situation, Task, Action, Result).
- Round 4 — Domain / Hiring Manager: For quantitative or fintech roles, expect probability, statistics, or financial math questions. The hiring manager may also deep-dive into past projects.
Hiring Decision:
- Interviewers submit independent feedback; a hiring committee makes the final call.
- Offers include competitive base salary, annual performance bonuses, RSUs (for senior roles), and comprehensive benefits.
- Campus Technology Analyst offers come with structured onboarding, mentorship, and rotation programs.
- Unsuccessful candidates can typically reapply after 6–12 months.
Frequently Tested Topics at JP Morgan
Based on interview reports, JP Morgan's assessments strongly focus on the following areas. Prioritize these during your preparation:
- Arrays & Strings: Sliding window, two-pointer, prefix sums, frequency maps — fundamental to almost every round.
- Dynamic Programming: Knapsack variants, LCS, LIS, matrix DP. JP Morgan OA problems frequently include multi-dimensional DP.
- Trees & Graphs: BFS, DFS, topological sort, shortest path (Dijkstra, Bellman-Ford). Know both recursive and iterative approaches.
- Sorting & Searching: Merge sort, quickselect, binary search on answer. Efficiency is emphasized.
- Heap / Priority Queue: Used in scheduling, Top-K, and financial data stream problems.
- Hash Maps & Sets: Essential for O(1) lookups in interval, frequency, and grouping problems.
- Finance-Flavored Problems: Stock price analysis, portfolio optimization, transaction deduplication, order book simulation — JP Morgan uniquely includes these.
- System Design Fundamentals: Rate limiting, caching (LRU/LFU), message queues, distributed consensus — especially for experienced roles.
How to Use This Resource
Each question below includes:
- Difficulty — Easy / Medium / Hard
- Topic — the primary DSA concept being tested
- Constraints — to guide your complexity thinking
- Problem Statement — clear description of the task
- Example — sample input/output with explanation
Practice these on LeetCode, HackerRank, or Codility. Always aim to solve the problem optimally, then verbalize your approach as if explaining to an interviewer.
Additional Resources for Preparation
- Free mock test
- ATS Score checker & Resume optimization
- Roadmaps
- Interview questions
- Interview experience
- Resume Templates
- Free study notes
- Free placement material drive link
Tips for Success
- Code for Correctness First, Then Optimize: State the brute-force approach, explain why it is insufficient, then derive the optimal solution. JP Morgan interviewers reward structured thinking.
- Think About Scale: JP Morgan systems process millions of events per second. When asked to design or optimize, always factor in throughput, latency, and data volume.
- Master Clean Code Habits: Use meaningful variable names, consistent indentation, and brief inline comments. Interviewers note code quality, not just output correctness.
- Know Your Complexity: For every solution, be ready to state time and space complexity and justify it. Suboptimal complexity is a common rejection point.
- Understand Finance Concepts at a High Level: You don't need a finance degree, but knowing what a stock order book, bid-ask spread, or transaction ledger is will help you contextualize domain-specific problems.
- Behavioral Preparation: JP Morgan strongly values cultural alignment. Prepare 4–5 STAR stories covering leadership, handling conflict, delivering under pressure, and learning from failure.
- Practice Timed Sessions: JP Morgan OA problems have strict time limits. Simulate real conditions — 60 minutes, no distractions, implement and test your solution fully.
Good luck with your preparation!
JP Morgan Previous Year Coding Questions
The questions below are categorized by topic and tagged with difficulty. They cover JP Morgan's online assessments, phone screens, and on-site rounds. Work through them systematically — start with arrays and strings, then move to DP, trees/graphs, and finally the finance-flavored problems at the end.
Arrays & Strings
1. Two Sum
Difficulty: Easy | Topic: Arrays, Hash Map
Constraints: 2 ≤ nums.length ≤ 10⁴, -10⁹ ≤ nums[i] ≤ 10⁹, exactly one valid answer exists.
Problem Statement: Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. You may not use the same element twice.
Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9. Use a hash map to achieve O(n) time.
2. Longest Substring Without Repeating Characters
Difficulty: Medium | Topic: Sliding Window, Hash Map
Constraints: 0 ≤ s.length ≤ 5×10⁴, characters are English letters, digits, or symbols.
Problem Statement: Given a string s, find the length of the longest substring that contains no repeating characters.
Example:
Input: s = "abcabcbb"
Output: 3
Explanation: The longest substring without repeats is "abc". Use a sliding window with a character index map to keep the window valid in O(n).
3. Valid Parentheses
Difficulty: Easy | Topic: Stack, Strings
Constraints: 1 ≤ s.length ≤ 10⁴, s contains only (, ), {, }, [, ].
Problem Statement: Given a string s, determine if it is valid. A string is valid if every open bracket is closed by the same type of bracket in the correct order, and no open bracket is left unclosed.
Example:
Input: s = "{[()]}"
Output: true
Input: s = "(]"
Output: false
4. Product of Array Except Self
Difficulty: Medium | Topic: Arrays, Prefix/Suffix Products
Constraints: 2 ≤ nums.length ≤ 10⁵, -30 ≤ nums[i] ≤ 30. Must run in O(n), without using division.
Problem Statement: Given an integer array nums, return an array answer where answer[i] equals the product of all elements of nums except nums[i].
Example:
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Explanation: Build a left-product array and a right-product array, then multiply them together.
5. Trapping Rain Water
Difficulty: Hard | Topic: Arrays, Two Pointers
Constraints: 0 ≤ height.length ≤ 3×10⁴, 0 ≤ height[i] ≤ 10⁵.
Problem Statement: Given an array height representing an elevation map where each bar has width 1, compute how much water can be trapped between the bars after rain.
Example:
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Explanation: Use the two-pointer approach: maintain left_max and right_max. At each step, water at position i = min(left_max, right_max) - height[i].
6. Minimum Window Substring
Difficulty: Hard | Topic: Sliding Window, Hash Map
Constraints: 1 ≤ s.length ≤ 10⁵, 1 ≤ t.length ≤ 10⁴.
Problem Statement: Given strings s and t, return the minimum window substring of s that contains every character of t (including duplicates). If no such window exists, return an empty string.
Example:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: Expand the right pointer until the window is valid, then shrink from the left to find the minimum valid window.
7. Merge Intervals
Difficulty: Medium | Topic: Arrays, Sorting
Constraints: 1 ≤ intervals.length ≤ 10⁴, 0 ≤ start_i ≤ end_i ≤ 10⁴.
Problem Statement: Given an array of intervals, merge all overlapping intervals and return an array of non-overlapping intervals covering the entire range.
Example:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Sort by start time. Iterate and merge when the current interval's start is ≤ previous end.
8. Rotate Array
Difficulty: Medium | Topic: Arrays, In-place Manipulation
Constraints: 1 ≤ nums.length ≤ 10⁵, 0 ≤ k ≤ 10⁵.
Problem Statement: Given an integer array nums, rotate the array to the right by k steps. Try to solve it in O(1) extra space.
Example:
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Hint: Reverse the full array, then reverse the first k elements, then reverse the remaining n-k elements.
9. Longest Palindromic Substring
Difficulty: Medium | Topic: Strings, Expand Around Center
Constraints: 1 ≤ s.length ≤ 1000, s contains only lowercase English letters.
Problem Statement: Given a string s, return the longest palindromic substring in s.
Example:
Input: s = "babad"
Output: "bab" (or "aba")
Input: s = "racecar"
Output: "racecar"
Explanation: For each character (and each pair), expand outward while characters match. O(n²) time, O(1) space.
Linked Lists
10. Reverse Linked List
Difficulty: Easy | Topic: Linked List, Iteration/Recursion
Constraints: 0 ≤ number of nodes ≤ 5000, -5000 ≤ Node.val ≤ 5000.
Problem Statement: Given the head of a singly linked list, reverse the list and return the new head.
Example:
Input: [1 → 2 → 3 → 4 → 5]
Output: [5 → 4 → 3 → 2 → 1]
Hint: Use three pointers: prev, curr, next. Iterative solution runs in O(n) time and O(1) space.
11. Detect Cycle in Linked List
Difficulty: Easy | Topic: Linked List, Floyd's Cycle Detection
Constraints: 0 ≤ number of nodes ≤ 10⁴.
Problem Statement: Given the head of a linked list, return true if there is a cycle, otherwise false. Solve in O(1) extra space.
Example:
Input: [3 → 2 → 0 → -4], pos = 1 (tail connects to index 1)
Output: true
Explanation: Use slow and fast pointers. If they meet, a cycle exists.
12. Merge Two Sorted Linked Lists
Difficulty: Easy | Topic: Linked List, Two Pointers
Constraints: 0 ≤ number of nodes in each list ≤ 50, -100 ≤ Node.val ≤ 100.
Problem Statement: Given the heads of two sorted linked lists, merge them into one sorted linked list by splicing their nodes together. Return the head of the merged list.
Example:
Input: l1 = [1 → 2 → 4], l2 = [1 → 3 → 4]
Output: [1 → 1 → 2 → 3 → 4 → 4]
13. Find the Middle of a Linked List
Difficulty: Easy | Topic: Linked List, Two Pointers
Constraints: 1 ≤ number of nodes ≤ 100.
Problem Statement: Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second one.
Example:
Input: [1 → 2 → 3 → 4 → 5]
Output: Node 3
Input: [1 → 2 → 3 → 4 → 5 → 6]
Output: Node 4
Hint: Use the slow/fast pointer technique. When fast reaches the end, slow is at the middle.
Trees & Binary Search
14. Validate Binary Search Tree
Difficulty: Medium | Topic: Binary Tree, DFS, Recursion
Constraints: 1 ≤ number of nodes ≤ 10⁴, -2³¹ ≤ Node.val ≤ 2³¹ - 1.
Problem Statement: Given the root of a binary tree, determine if it is a valid BST. For every node, all values in its left subtree must be strictly less than its value, and all values in its right subtree must be strictly greater.
Example:
Input: [5, 1, 7] → false (right child 7 is correct, but example with [5, 1, 4, null, null, 3, 6] → false because 4 < 5 violates the BST property at root)
Hint: Pass min and max bounds through recursion. Avoid the common mistake of only comparing parent-child pairs.
15. Level Order Traversal of Binary Tree
Difficulty: Medium | Topic: Binary Tree, BFS
Constraints: 0 ≤ number of nodes ≤ 2000, -1000 ≤ Node.val ≤ 1000.
Problem Statement: Given the root of a binary tree, return its level-order traversal as a list of lists, where each inner list contains values at that level from left to right.
Example:
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Hint: Use a queue (BFS). At the start of each level, record the current queue size to know how many nodes to process for that level.
16. Serialize and Deserialize Binary Tree
Difficulty: Hard | Topic: Binary Tree, BFS/DFS, String Encoding
Constraints: 0 ≤ number of nodes ≤ 10⁴, -1000 ≤ Node.val ≤ 1000.
Problem Statement: Design an algorithm to serialize a binary tree into a string and deserialize the string back into the original tree structure.
Example:
Input: root = [1, 2, 3, null, null, 4, 5]
Serialized: "1,2,3,#,#,4,5"
Deserialized: Original tree reconstructed exactly.
Note: Your encoding scheme is your choice — level-order with null markers is the most common approach.
17. Search in Rotated Sorted Array
Difficulty: Medium | Topic: Binary Search
Constraints: 1 ≤ nums.length ≤ 5000, -10⁴ ≤ nums[i] ≤ 10⁴, all values are unique.
Problem Statement: Given a sorted array rotated at an unknown pivot index, and a target integer, return the index of target if it exists, otherwise -1. Your solution must run in O(log n) time.
Example:
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output: 4
Hint: At each step of binary search, determine which half is sorted. The target must be in the sorted half if it falls within that range.
18. Find First and Last Position of Element in Sorted Array
Difficulty: Medium | Topic: Binary Search
Constraints: 0 ≤ nums.length ≤ 10⁵, -10⁹ ≤ nums[i] ≤ 10⁹, must run in O(log n).
Problem Statement: Given a sorted array and a target, return [first_index, last_index] of the target. Return [-1, -1] if not found.
Example:
Input: nums = [5, 7, 7, 8, 8, 10], target = 8
Output: [3, 4]
Hint: Run binary search twice — once biased toward the left boundary, once toward the right.
Graphs
19. Number of Islands
Difficulty: Medium | Topic: Graphs, BFS/DFS, Matrix
Constraints: 1 ≤ rows, cols ≤ 300, grid[i][j] is '0' or '1'.
Problem Statement: Given a 2D grid of '1' (land) and '0' (water), count the number of islands. An island is a group of adjacent land cells (horizontally or vertically connected) surrounded by water.
Example:
Input:
11110
11010
11000
00000
Output: 1
Hint: For each unvisited '1', launch a DFS/BFS to mark all connected land as visited. Each launch = one island.
20. Course Schedule (Cycle Detection)
Difficulty: Medium | Topic: Graphs, Topological Sort, DFS
Constraints: 1 ≤ numCourses ≤ 2000, 0 ≤ prerequisites.length ≤ 5000.
Problem Statement: Given numCourses courses and a list of prerequisite pairs [a, b] (take b before a), determine if it is possible to complete all courses. Return true if possible, false if a cycle exists.
Example:
Input: numCourses = 2, prerequisites = [[1, 0]]
Output: true
Input: numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Output: false (circular dependency)
21. Word Search in Grid
Difficulty: Medium | Topic: Backtracking, DFS, Matrix
Constraints: 1 ≤ rows, cols ≤ 6, 1 ≤ word.length ≤ 15.
Problem Statement: Given a 2D board of characters and a string word, return true if word exists in the grid formed by sequentially adjacent cells (up/down/left/right). The same cell may not be used more than once per path.
Example:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Hint: Use DFS with backtracking. Mark cells as visited in-place and restore them after recursion.
Dynamic Programming
22. Coin Change
Difficulty: Medium | Topic: Dynamic Programming (Unbounded Knapsack)
Constraints: 1 ≤ coins.length ≤ 12, 1 ≤ coins[i] ≤ 2³¹ - 1, 0 ≤ amount ≤ 10⁴.
Problem Statement: Given an array of coin denominations and an amount, return the minimum number of coins needed to make the amount. Return -1 if it is impossible.
Example:
Input: coins = [1, 5, 6, 9], amount = 11
Output: 2 (5 + 6 = 11)
Input: coins = [2], amount = 3
Output: -1
23. Longest Common Subsequence
Difficulty: Medium | Topic: Dynamic Programming (2D DP)
Constraints: 1 ≤ text1.length, text2.length ≤ 1000, strings contain only lowercase English letters.
Problem Statement: Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence does not need to be contiguous.
Example:
Input: text1 = "abcde", text2 = "ace"
Output: 3 (the LCS is "ace")
Hint: Define dp[i][j] = LCS length of text1[0..i-1] and text2[0..j-1]. Recurrence: if chars match, dp[i][j] = dp[i-1][j-1] + 1; else max(dp[i-1][j], dp[i][j-1]).
24. Maximum Subarray (Kadane's Algorithm)
Difficulty: Medium | Topic: Dynamic Programming, Arrays
Constraints: 1 ≤ nums.length ≤ 10⁵, -10⁴ ≤ nums[i] ≤ 10⁴.
Problem Statement: Given an integer array nums, find the contiguous subarray with the largest sum and return that sum.
Example:
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6 (subarray [4, -1, 2, 1])
Hint: Track current_sum and max_sum. If current_sum < 0, reset to 0.
25. Climbing Stairs
Difficulty: Easy | Topic: Dynamic Programming, Fibonacci
Constraints: 1 ≤ n ≤ 45.
Problem Statement: You are climbing n stairs. Each time you can climb 1 or 2 steps. Return the number of distinct ways to reach the top.
Example:
Input: n = 5
Output: 8 (the pattern follows Fibonacci: dp[n] = dp[n-1] + dp[n-2])
26. Longest Increasing Subsequence
Difficulty: Medium | Topic: Dynamic Programming, Binary Search
Constraints: 1 ≤ nums.length ≤ 2500, -10⁴ ≤ nums[i] ≤ 10⁴.
Problem Statement: Given an integer array nums, return the length of the longest strictly increasing subsequence.
Example:
Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]
Output: 4 (the LIS is [2, 3, 7, 101])
Hint: The O(n log n) solution uses patience sorting with a tails array and binary search.
27. Maximum Product Subarray
Difficulty: Medium | Topic: Dynamic Programming, Arrays
Constraints: 1 ≤ nums.length ≤ 2×10⁴, -10 ≤ nums[i] ≤ 10.
Problem Statement: Given an integer array nums, find the contiguous subarray with the largest product and return the product.
Example:
Input: nums = [2, 3, -2, 4]
Output: 6 (subarray [2, 3])
Hint: Track both max_product and min_product (because multiplying two negatives yields a positive).
Heap & Priority Queue
28. Top K Frequent Elements
Difficulty: Medium | Topic: Hash Map, Heap (Min-Heap)
Constraints: 1 ≤ nums.length ≤ 10⁵, k is in range [1, number of unique elements].
Problem Statement: Given an integer array nums and an integer k, return the k most frequently occurring elements in any order.
Example:
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]
Hint: Count frequencies with a hash map, then use a min-heap of size k to maintain the top-k elements.
29. K-th Largest Element in an Array
Difficulty: Medium | Topic: Heap, Quickselect
Constraints: 1 ≤ k ≤ nums.length ≤ 10⁵, -10⁴ ≤ nums[i] ≤ 10⁴.
Problem Statement: Given an integer array nums and integer k, return the k-th largest element (not the k-th distinct).
Example:
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
Hint: A min-heap of size k gives O(n log k). Quickselect gives O(n) average.
Design & Data Structures
30. Implement LRU Cache
Difficulty: Medium | Topic: Design, Hash Map + Doubly Linked List
Constraints: 1 ≤ capacity ≤ 3000, both get and put must run in O(1) average.
Problem Statement: Design a data structure implementing a Least Recently Used (LRU) cache. Implement get(key) (return value or -1 if not found) and put(key, value) (insert/update, evicting LRU entry when at capacity).
Example:
LRUCache cache = new LRUCache(2);
cache.put(1, 1); cache.put(2, 2);
cache.get(1); → 1
cache.put(3, 3); (evicts key 2)
cache.get(2); → -1
Hint: Combine a hash map (for O(1) access) with a doubly linked list (for O(1) insertion/deletion at both ends).
31. Find Duplicate Number
Difficulty: Medium | Topic: Arrays, Floyd's Cycle Detection
Constraints: nums.length = n+1, each integer in [1, n], exactly one duplicate — do not modify array, O(1) space.
Problem Statement: Given an array of n+1 integers where each value is in [1, n], find the one duplicate number without modifying the array.
Example:
Input: nums = [1, 3, 4, 2, 2]
Output: 2
Hint: Treat array indices as a linked list (index → nums[index]). A cycle exists at the duplicate. Apply Floyd's tortoise and hare algorithm.
32. Subsets (Power Set)
Difficulty: Medium | Topic: Backtracking, Bit Manipulation
Constraints: 1 ≤ nums.length ≤ 10, all elements are unique.
Problem Statement: Given an integer array nums of unique elements, return all possible subsets (the power set). The solution must not contain duplicate subsets.
Example:
Input: nums = [1, 2, 3]
Output: [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
Hint: Use iterative approach — for each new element, add it to every existing subset.
Finance-Flavored Coding Problems
JP Morgan uniquely includes problems inspired by financial systems. These are commonly reported in OA rounds and domain interviews.
33. Best Time to Buy and Sell Stock — Multiple Transactions
Difficulty: Medium | Topic: Arrays, Greedy
Constraints: 1 ≤ prices.length ≤ 3×10⁴, 0 ≤ prices[i] ≤ 10⁴.
Problem Statement: Given a stock price array prices where prices[i] is the price on day i, find the maximum profit you can achieve by completing as many transactions as you like (you must sell before buying again).
Example:
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 7
Explanation: Buy at 1, sell at 5 (profit 4). Buy at 3, sell at 6 (profit 3). Total = 7.
Insight: Any upward slope contributes to profit — sum all positive day-to-day differences.
34. Maximum Profit with at Most K Transactions
Difficulty: Hard | Topic: Dynamic Programming (Finance)
Constraints: 0 ≤ k ≤ 100, 0 ≤ prices.length ≤ 1000.
Problem Statement: Given a stock price array and an integer k representing the maximum number of transactions allowed (buy + sell = 1 transaction), find the maximum profit. You must sell before buying again.
Example:
Input: k = 2, prices = [3, 2, 6, 5, 0, 3]
Output: 7
Explanation: Buy at 2, sell at 6 (profit 4). Buy at 0, sell at 3 (profit 3). Total = 7.
Hint: Define dp[i][j] = max profit using at most i transactions through day j. Handle the edge case where k ≥ n/2 separately (unlimited transactions).
35. Transaction Fee — Maximize Stock Profit
Difficulty: Medium | Topic: Dynamic Programming, Greedy (Finance)
Constraints: 1 ≤ prices.length ≤ 5×10⁴, 1 ≤ prices[i] ≤ 5×10⁴, 0 ≤ fee ≤ 5×10⁴.
Problem Statement: Given an array prices and a transaction fee, find the maximum profit by completing as many transactions as desired (each transaction incurs a fee applied once per buy-sell cycle). You cannot hold more than one share at a time.
Example:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: Transactions: buy at 1 sell at 8 (profit 5), buy at 4 sell at 9 (profit 3). Total = 8.
Hint: Maintain two states — cash (max profit holding no stock) and hold (max profit holding one stock). Transition at each price.
36. Running Median of a Data Stream
Difficulty: Hard | Topic: Heap, Design (Finance)
Constraints: 0 ≤ num ≤ 10⁵, at most 5×10⁴ calls to addNum and findMedian.
Problem Statement: Design a data structure that supports adding integers from a data stream and finding the median of all elements added so far, in O(log n) per add and O(1) per query.
Example:
addNum(1) → median = 1.0
addNum(2) → median = 1.5
addNum(3) → median = 2.0
Explanation: Maintain two heaps — a max-heap for the lower half and a min-heap for the upper half — keeping them balanced in size at all times.
Real-world relevance: This pattern appears in real-time financial analytics where running statistics on a price stream are required.
37. Rate Limiter — Sliding Window Counter
Difficulty: Medium | Topic: Design, Sliding Window (Finance/Systems)
Problem Statement: Design a rate limiter that allows at most N requests per T seconds for a given user. Implement two methods: isAllowed(userId, timestamp) — returns true if the request at the given timestamp should be allowed, false otherwise.
Example:
Rate limit: 3 requests per 10 seconds.
isAllowed("user1", 1) → true (1 request)
isAllowed("user1", 5) → true (2 requests)
isAllowed("user1", 9) → true (3 requests)
isAllowed("user1", 10) → false (still 3 within window [1, 10])
isAllowed("user1", 12) → true (window shifts, request at 1 falls out)
Real-world relevance: JP Morgan's trading APIs enforce per-client rate limits to prevent market manipulation and ensure fair access.
38. Order Book Matching Engine (Simulation)
Difficulty: Hard | Topic: Design, Priority Queue, Sorting (Finance)
Problem Statement: Simulate a simple stock order book. You receive a stream of buy orders (with price and quantity) and sell orders (with price and quantity). Match orders using the rule: a buy order matches a sell order when the buy price ≥ sell price. Process orders in FIFO order for equal prices. For each matched trade, output the trade price and quantity. Return all remaining unmatched orders at the end.
Example:
Orders: BUY 100 shares at $50, SELL 100 shares at $48, BUY 50 shares at $45, SELL 50 shares at $52
Matched: 100 shares at $48 (buy $50 ≥ sell $48)
Remaining: BUY 50 @ $45, SELL 50 @ $52 (no match since $45 < $52)
Hint: Use a max-heap for buy orders (highest price has priority) and a min-heap for sell orders (lowest price has priority).
Real-world relevance: This is the core of a stock exchange matching engine — a fundamental system at any investment bank's trading technology division.
39. Detect Arbitrage Opportunity (Currency Exchange)
Difficulty: Hard | Topic: Graphs, Bellman-Ford (Finance)
Problem Statement: Given an n×n matrix rates where rates[i][j] is the exchange rate from currency i to currency j, determine if an arbitrage opportunity exists (a cycle where you can start with 1 unit of currency X, convert through a sequence of currencies, and end up with more than 1 unit of currency X).
Example:
rates =
USD → EUR: 0.9, EUR → GBP: 0.8, GBP → USD: 1.5
Product: 0.9 × 0.8 × 1.5 = 1.08 > 1 → Arbitrage exists!
Hint: Take the negative log of each rate. An arbitrage cycle becomes a negative-weight cycle. Apply Bellman-Ford to detect it.
Real-world relevance: Quantitative developers and algo trading teams at JP Morgan regularly build systems to identify and act on arbitrage opportunities across markets.
40. Portfolio Rebalancing
Difficulty: Medium | Topic: Greedy, Sorting (Finance)
Problem Statement: You are given a portfolio of n assets, each with a current allocation percentage and a target allocation percentage. To rebalance, you can transfer value between assets. Each transfer has a cost equal to 0.1% of the amount transferred. Find the minimum total cost to rebalance the portfolio to the target allocation, given a total portfolio value of V.
Example:
V = 100,000
Assets: [A: current 40%, target 30%], [B: current 20%, target 35%], [C: current 40%, target 35%]
Excess: A = 10,000, C = 5,000. Deficit: B = 15,000.
Transfers: A→B 10,000 (cost 10), C→B 5,000 (cost 5). Total cost = $15.
Hint: Compute excess and deficit for each asset. Greedily match surpluses to deficits. The minimum total transferred amount (= total surplus = total deficit) determines cost.