Arrays & Hashing
- Recognize the array and hashing problems that open most JPMorgan coding rounds, led by Two Sum
- Drill two reusable hash-map skeletons: the complement lookup and the prefix-sum counter
- Write plain, correct Java that runs on the first or second try, the way JPMorgan grades speed with accuracy
Arrays and hashing are where a JPMorgan coding round starts, and they are the friendliest place to start. This is the largest single slice of what gets asked, around 15 to 20% of reported problems. Two Sum is the single most-repeated problem by candidate reports, usually the opener in the two-problem round. The bar here rewards breadth: reach for the right structure quickly, and write code a teammate could read at a glance.
Nearly every problem in this band comes down to one trade: spend a little memory to buy back time. A hash map turns a question you would otherwise answer by re-scanning the array, has this value appeared, which index held it, how many earlier prefixes summed to this, into a single constant-time lookup. Learn to hear that repeated lookup inside a prompt and most of the band collapses into a few clean lines. Spot the lookup, and the rest is bookkeeping.
How JPMorgan frames it
JPMorgan keeps these problems close to the canonical form, sometimes dressed in the bank's own world. Two Sum arrives as two ledger entries whose amounts reach a target, and a subarray-sum question becomes a count of contiguous transactions that clear a figure. The story on the surface changes, but the pattern underneath is the standard easy-to-medium canon, and your job is to name that pattern fast rather than get lost in the framing.
The round is Java-first, and the loop rewards Java that reads plainly. A HashMap with getOrDefault, a single pass, self-documenting names, and no cleverness for its own sake is exactly what earns the pass. The online assessment runs two problems in about an hour on HackerRank and scores how fast you reach a passing solution, so these mediums have to come out without hesitation. Speed with accuracy is the grade.
HashMap, name your variables for what they hold, and keep the single pass single. A clever one-liner that hides a bug costs you more here than a straightforward loop that clearly runs, because half the round is about whether your code survives another engineer reading it.The unifying move on this band is replacing a search with a lookup. A brute-force Two Sum checks every pair because it keeps asking "is the partner I need somewhere in the array." Store what you have already seen in a hash map and that question becomes a single membership test. The same trade drives the subarray counter: instead of re-summing every range, you remember how many prefixes you have already passed and read the answer straight out of the map. Once you spot the repeated lookup, the structure writes itself.
The two templates to know
Two skeletons cover most of this band. Type each in Java until it is automatic, so in the room your attention goes to the prompt and the follow-up while the machinery runs from memory.
Pattern 1: The complement lookup
Reach for a single hash map when a problem asks whether a matching value exists as you scan. You walk the array once, and at each element you ask the map a question about what you have already passed. For a pair-sum the question is "have I seen the complement," the value that would complete the target. You answer before inserting the current element, which keeps you from pairing an element with itself.
int[] twoSum(int[] nums, int target) { Map<Integer, Integer> seen = new HashMap<>(); // value -> index we've passed for (int i = 0; i < nums.length; i++) { int need = target - nums[i]; // the partner that completes the pair if (seen.containsKey(need)) { // its partner came earlier return new int[]{ seen.get(need), i }; // earlier index first } seen.put(nums[i], i); // remember this one for a later partner } return new int[]{}; // no pair reaches the target}Correctness rests on the order of the two lines inside the loop. You check for the complement first, then store the current element, so an element can never match against itself. Flip those two lines and a target of exactly twice an element would return the same index twice. One pass, one map, and the lookup is what turns the quadratic pair-scan into linear time.
Pattern 2: The prefix-sum counter
When a problem asks about contiguous runs that sum to a value, keep a running total as you scan and store how many times each running total has occurred. A run from some earlier point up to here sums to the target exactly when the running total once equalled the current total minus the target. So at each step you look up that earlier total in the map and add its count.
int countSubarrays(int[] nums, int k) { int count = 0, running = 0; Map<Integer, Integer> prefixCounts = new HashMap<>(); prefixCounts.put(0, 1); // one empty prefix sums to 0 for (int value : nums) { running += value; // prefix sum up to here // a run ending here sums to k when an earlier prefix == running - k count += prefixCounts.getOrDefault(running - k, 0); prefixCounts.merge(running, 1, Integer::sum); // record this prefix } return count;}Seeding the map with {0: 1} is the line people forget, and it is what lets a run that starts at index zero count. Without it, a prefix that already equals the target has no earlier zero to match against. This template handles negative values cleanly, unlike a sliding window, because it never assumes growing the range raises the sum. That is exactly why the hash-map version is the one to reach for when the values are not guaranteed positive.
Asked at JPMorgan
Three problems JPMorgan leans on in this band, one anchored on the complement lookup and one on the prefix counter, plus the bucketing variant that rounds out the hashing toolkit. Each test case is the function's arguments as a JSON array and the expected return. The worked solutions are shown in Python for brevity; the editor ships a six-language stub, Java included, so drill whichever you will write in the room.
Two Sum: One-Pass Hash Map
Problem
nums, a list of ledger entry amounts, and an integer target. Return the indices of the two entries whose amounts add up to target, with the smaller index first.Each input has exactly one answer, and you may not use the same entry twice.
Input encoding. Each test case is a JSON array
[nums, target]. The function returns the two indices as a list.Input: nums = [2,7,11,15], target = 9
Output: [0,1]
nums[0] + nums[1] = 2 + 7 = 9.
Input: nums = [3,2,4], target = 6
Output: [1,2]
nums[1] + nums[2] = 2 + 4 = 6.
Input: nums = [3,3], target = 6
Output: [0,1]
The two equal entries at different indices sum to 6.
Walk the array once, keeping a map from value to the index you saw it at. At each entry, check whether the complement target minus value is already in the map before you insert the current one.
Two Sum: One-Pass Hash Map
Click "Run" to execute your code
Test Cases
[[2,7,11,15],9]Expected: [0,1][[3,2,4],6]Expected: [1,2][[3,3],6]Expected: [0,1][[-1,-2,-3,-4,-5],-8]Expected: [2,4][[0,4,3,0],0]Expected: [0,3][[1,5,9,13],14]Expected: [1,2]Subarray Sum Equals K: Prefix Sums With a Hash Map
Problem
nums, a list of signed transaction amounts, and an integer k. Return the number of contiguous runs of transactions whose amounts sum to exactly k.Amounts may be negative, since a run can mix debits and credits.
Input encoding. Each test case is a JSON array
[nums, k]. The function returns the count as an integer.Input: nums = [1,1,1], k = 2
Output: 2
The runs [1,1] at indices 0-1 and 1-2 each sum to 2.
Input: nums = [1,2,3], k = 3
Output: 2
The runs [1,2] and [3] both sum to 3.
Input: nums = [1,-1,0], k = 0
Output: 3
The runs [1,-1], [1,-1,0], and [0] all sum to 0.
Keep a running prefix sum and a map from each prefix sum to how many times it has occurred. A run ending here sums to k whenever an earlier prefix equals the running sum minus k, so add that prefix's count.
Subarray Sum Equals K: Prefix Sums With a Hash Map
Click "Run" to execute your code
Test Cases
[[1,1,1],2]Expected: 2[[1,2,3],3]Expected: 2[[1,-1,0],0]Expected: 3[[3,4,7,2],7]Expected: 2[[1],0]Expected: 0[[-1,-1,1],0]Expected: 1k rather than the count. The structure holds, but you store the first index at which each prefix sum appeared instead of a count, so you can measure the widest span back to a matching earlier prefix. Storing the earliest index is the key change, since an earlier start gives a longer run. The longest-run variant is worked through below.Group Anagrams: Bucket by Signature
Problem
words, group together the ones that are anagrams of each other. Two words are anagrams when one is a rearrangement of the other's letters.Return the groups sorted: sort the words inside each group, then sort the groups themselves, so the output is deterministic.
Input encoding. Each test case is a JSON array
[words], a single list argument. The function returns a list of groups.Input: words = ["eat","tea","tan","ate","nat","bat"]
Output: [["ate","eat","tea"],["bat"],["nat","tan"]]
eat, tea, ate share the letters aet; tan, nat share ant; bat stands alone.
Input: words = [""]
Output: [[""]]
A single empty string forms one group.
Input: words = ["a"]
Output: [["a"]]
A single one-letter word forms one group.
Give every word a signature that all its anagrams share, its letters in sorted order, and use that signature as a hash-map key. Words with the same signature land in the same bucket.
Group Anagrams: Bucket by Signature
Click "Run" to execute your code
Test Cases
[["eat","tea","tan","ate","nat","bat"]]Expected: [["ate","eat","tea"],["bat"],["nat","tan"]][[""]]Expected: [[""]][["a"]]Expected: [["a"]][["abc","bca","cab","xyz","zyx"]]Expected: [["abc","bca","cab"],["xyz","zyx"]][["listen","silent","enlist","google","gogole"]]Expected: [["enlist","listen","silent"],["gogole","google"]]Key Takeaways
- ✓Arrays and hashing are the largest slice of the JPMorgan coding round, around 15 to 20% of reported problems, and Two Sum is the single most-repeated problem and usually the opener. The bar is the right structure fast, written as plain Java a reviewer could sign off on.
- ✓The band comes down to one trade: spend a little memory on a hash map to replace a repeated search with a constant-time lookup. Learn to hear the repeated lookup in a prompt and the structure writes itself.
- ✓Two skeletons cover most of it: the complement lookup for pair-and-membership questions, and the prefix-sum counter for contiguous runs. Reach for the prefix counter over a sliding window whenever the values can be negative, as a ledger of debits and credits will be.
- ✓Group Anagrams tests the third corner, designing a shared hash key. Any value that is identical across a group and different across groups works, which is what lets the count-key follow-up drop the sort.
JPMorgan interview guideKnow what JPMorgan asks before you walk in.
15 coding · 3 system design · 18 behavioral questions
Get their questions first.
InterviewLegend is independent and not affiliated with or endorsed by any company it covers.