InterviewLegend

Arrays & Hashing

Alex Chen22 min readUpdated 183 real interview reports
In this lesson
  • 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.

The JPMorgan angle
Write it as plain Java a reviewer could sign off on. JPMorgan pairs the coding round with a code-review exercise, so the interviewer is already reading your code the way a teammate reads a pull request. Reach for a 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.

java
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.

java
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.

The JPMorgan angle
The moment you hear "count the runs that sum to X," a prefix counter beats a sliding window. A window gets away with it while the numbers stay positive. Then one negative amount breaks it, and a ledger of debits and credits always has one. The prefix-sum-plus-hash-map version never depends on the values being positive, so it is the safe default. Naming that up front is the kind of judgment the code-review culture at JPMorgan rewards.

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.

The JPMorgan angle
Drill these for speed as much as correctness, because the online assessment scores both. The HackerRank round gives you two problems in about an hour and grades how fast you reach a passing solution. A strong score is sometimes still passed over, so a clean first attempt matters. Time yourself on Two Sum and one subarray problem back to back until the hash-map reflex comes out without hesitation. That frees the Superday round for thinking through the code-review half rather than remembering the pattern.
1

Two Sum: One-Pass Hash Map

EasyFrequently asked
Problem
You are given 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.

How this uses the pattern

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

Loading...
Click "Run" to execute your code

Test Cases

Input: [[2,7,11,15],9]Expected: [0,1]
Input: [[3,2,4],6]Expected: [1,2]
Input: [[3,3],6]Expected: [0,1]
Input: [[-1,-2,-3,-4,-5],-8]Expected: [2,4]
Input: [[0,4,3,0],0]Expected: [0,3]
Input: [[1,5,9,13],14]Expected: [1,2]
The JPMorgan angle
Two Sum is the single most-repeated JPMorgan problem by candidate reports, and it is usually the opener in the two-problem round. The interviewer is watching for one thing above all: whether you reach for a hash map and a single pass, or start nesting two loops. The one-pass hash map is what they want to see written cleanly and quickly, because it is the clearest signal that you pick the right structure by reflex.
Take it further
A common variant asks you to return every distinct value-pair that sums to the target rather than one index pair. The work moves from a lookup to a sweep that dedupes as it goes. Sort the values, run two pointers inward, and skip over equal neighbors on both sides so each pair is emitted once. A separate variant asks what breaks if no solution is guaranteed, at which point you return an empty result when the loop finishes without a hit. The distinct-pairs version is worked through below.
2

Subarray Sum Equals K: Prefix Sums With a Hash Map

MediumCommonly asked
Problem
You are given 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.

How this uses the pattern

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

Loading...
Click "Run" to execute your code

Test Cases

Input: [[1,1,1],2]Expected: 2
Input: [[1,2,3],3]Expected: 2
Input: [[1,-1,0],0]Expected: 3
Input: [[3,4,7,2],7]Expected: 2
Input: [[1],0]Expected: 0
Input: [[-1,-1,1],0]Expected: 1
The JPMorgan angle
This is the subarray-sum family JPMorgan reuses in the medium slot, and it separates the candidates who reach for prefix sums from the ones who try to bend a sliding window onto it. Because the transaction amounts can be negative, a window breaks and a prefix-sum map does not. The interviewer is checking whether you spot that the values are signed and pick the structure that survives it, which is the same judgment the code-review round tests.
Take it further
A frequent turn asks for the length of the longest run summing to k 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.
3

Group Anagrams: Bucket by Signature

MediumCommonly asked
Problem
Given a list of strings 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.

How this uses the pattern

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

Loading...
Click "Run" to execute your code

Test Cases

Input: [["eat","tea","tan","ate","nat","bat"]]Expected: [["ate","eat","tea"],["bat"],["nat","tan"]]
Input: [[""]]Expected: [[""]]
Input: [["a"]]Expected: [["a"]]
Input: [["abc","bca","cab","xyz","zyx"]]Expected: [["abc","bca","cab"],["xyz","zyx"]]
Input: [["listen","silent","enlist","google","gogole"]]Expected: [["enlist","listen","silent"],["gogole","google"]]
The JPMorgan angle
Group Anagrams is a recurring JPMorgan hashing problem, and it tests a different corner of the same skill: designing a key. Any value that maps every member of a group to one identical key will do. The interviewer wants to see you pick a signature that is cheap to compute and provably shared, rather than comparing every pair of words. It is the "bucket by a derived key" move that shows up across the bank's medium problems.
Take it further
The standard follow-up asks you to drop the sort from the key so the whole solution stays linear in the total input size. Replace the sorted string with a fixed 26-length count of each letter, rendered as a tuple or a delimited string, which two anagrams always share. Building that count is linear in the word length instead of the sort's log factor. The count-key variant is worked through below.

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.
Had your JPMorgan interview?Tell us what they asked. Reviewed before it goes in, never with your name.
JPMorgan interview guide

Know what JPMorgan asks before you walk in.

15 coding · 3 system design · 18 behavioral questions

Get Premium$49 a year · Cancel anytime
Or start freeNo card.

Get their questions first.

InterviewLegend is independent and not affiliated with or endorsed by any company it covers.