InterviewLegend

Arrays & Hashing

Alex Chen24 min readUpdated 970 real interview reports
In this lesson
  • Collapse a nested loop into one hash-map pass before the brute force times out
  • Learn the two skeletons here: a one-pass frequency map and a complement lookup
  • Spot the four question shapes that all resolve to the same hash map
  • Practice the follow-ups Oracle pivots to, like O(1) extra space or returning the run

Watch for the moment your hand reaches to loop over the array a second time. That reflex is the tell that a hash map belongs there instead, holding the answer you already computed so you read it back in constant time rather than deriving it again. The whole cluster runs on that one instinct. Arrays and hashing is the largest slice of the Oracle loop, close to a quarter of the coding questions. It sits right at Oracle's bar of easy to medium. There's no exotic algorithm. You crack these by noticing that a double loop collapses into a single pass.

That instinct is worth more here than a bag of tricks, because Oracle grades on an editor that has to compile and pass the test cases. A tidy brute-force double loop reads fine and then times out on the large inputs, so reach for the O(n) hash-map version; it is the difference between green and red. The move to learn is small and it repeats: count things with a map, or look things up by key, and let the map turn a second scan into one lookup.

The Oracle angle
You meet this cluster more than any other, so fluency here clears a large share of the loop. Oracle's coding bar is easy to medium, with medium the mode. Arrays with hashing is the biggest single slice of it. A candidate quick with medium array and string problems walks through most Oracle rounds, and the reason is that the live editor has to compile and pass. An O(n) hash-map pass clears the big cases inside the time limit; a clean O(n squared) that reads well still fails them. So the signal the interviewer is really watching for is whether you reach for the map before the second loop.
  • Where the volume is: Arrays and hashing. The largest coding cluster in the Oracle loop, close to a quarter of the questions. Counting, membership, and pair-finding on arrays and strings, almost always solved by putting the answer in a map.
  • The compiler gate: An editor that must pass. Live rounds run on an online compiler, and your code has to build and clear the test cases. A working O(n) map pass beats a clean double loop that times out on the large inputs, and partial passes are recoverable.
  • What earns the point: The optimal, reasoned from brute force. Say the double loop out loud, name why it is slow, then replace the inner scan with a map lookup. Holding the empty input and the repeated value is half the score.
  • How it escalates: Drop the sort, or hold O(1) space. A working answer is the opening. Oracle escalates by taking the sort away, capping extra memory at constant, or asking for every matching pair, and grades the judgment more than the first version.

The one move: trade a scan for a lookup

Almost every problem in this cluster is the same swap. A brute force answers a question by scanning the array again, which stacks a second loop on the first and lands at O(n squared). A hash map answers the same question in constant time, so the second scan disappears and the pass drops to O(n). Two skeletons cover most of it. One counts, the other looks up by key or complement. Learn to see which one a problem is asking for and the code writes itself.

Count with a frequency map

python
# Count how many times each item appears, in one pass.
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1 # an unseen item reads as 0, then +1
# The standard counter does the same thing in one line.
from collections import Counter
counts = Counter(items) # {item: how_many_times_it_appears}

A frequency map answers every counting question in one pass. You walk the input once and bump each item's tally, so by the end the map holds how many times each value showed up. Anything that asks how many, or which value is most common, or whether two collections hold the same multiset of items, is this map with a different question asked at the end. The get(item, 0) default is the small detail that keeps it branchless: a value you have never seen reads as zero, so the first sighting becomes a one without a separate check.

Look up the complement

python
# "Is the value that completes this one already on the board?"
seen = {} # value -> where we saw it
for i, value in enumerate(nums):
partner = target - value # the number that finishes the pair
if partner in seen: # walked past it already?
return [seen[partner], i] # earliest index first
seen[value] = i # remember this value for later

The second skeleton flips the question from counting to membership. Instead of asking how many, you ask whether the partner you need is already in the map. You walk the array once, and at each number you compute the value that would complete your goal, then check the map for it before storing the current number. Because the check happens before the store, a number never pairs with itself, and the first complete pair you return is the earliest one. That single lookup replaces the inner loop a brute force would run, which is the whole reason the pass is O(n) and not O(n squared).

The names change, the shape does not. Four questions all resolve to a hash map. Have I seen this before? How many times does this appear? Which items share a property? Is there a partner that completes this one? The first is a set and the second a counter. The third is a bucket keyed by the shared trait, the fourth a complement lookup. When a problem statement matches one of those four, you know the data structure before you know the details.

The Oracle angle
Oracle is a database company, and a hash map is the primitive its engine runs on. A hash join pairs rows from two tables in one pass instead of comparing every row against every other. A hash index finds a row by key without scanning the table. That is the same trade you make when a double loop becomes a lookup. Sometimes an interviewer asks you to build the count yourself, or bans a built-in and says to solve it without the library helper. They're checking that you own the mechanism behind the method name. Write the map by hand, keep the pass O(n), and be ready to say why the lookup is constant time on average and where it degrades.

Asked at Oracle

Three problems, one per flavor of the move. The first buckets words by a shared signature, the second looks up a complement, the third leans on set membership to stay linear. Get the base version compiling and passing the corners first, especially an empty input and a repeated value. Then each walkthrough carries the Oracle follow-up, such as dropping the sort, holding O(1) extra space, or returning the run itself.

1

Group Anagrams: Bucket by Signature

MediumCommonly asked
Problem
Given an array of strings words, group the anagrams together and return the groups. Two strings are anagrams when one is a rearrangement of the other's letters. The groups may be returned in any order, and the words within a group may be in any order. Assume lowercase English letters.

Build the grouping with a hash map. Sorting the whole list and eyeballing runs is not the exercise.

Input encoding. A test case is a JSON array of the input words. The expected value is the list of groups.

Input: words = ["eat","tea","tan","ate","nat","bat"]

Output: [["eat","tea","ate"],["tan","nat"],["bat"]]

eat, tea, and ate share the letters a, e, t. tan and nat share a, n, t. bat stands alone.

Input: words = [""]

Output: [[""]]

A single empty string forms one group by itself.

Input: words = ["a"]

Output: [["a"]]

One word, one group.

How this uses the pattern

Map a computed signature to a bucket of words. Every anagram produces the same signature, so appending each word to its signature's bucket groups them in one pass.

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","noon","noon"]]Expected: [["abc","bca","cab"],["noon","noon"],["xyz","zyx"]]
Input: [["ddddddddddg","dgggggggggg"]]Expected: [["ddddddddddg"],["dgggggggggg"]]
The Oracle angle
Grouping items that share a derived property is the purest form of the hashing move, and Oracle likes it because the key is not sitting in the data, you have to compute it. The signature is whatever collapses all anagrams to one value: the sorted letters, or a count of each letter. The interviewer is watching you build the bucket map and keep it a single pass, never comparing every word against every other. It is really any "group the records that match on a computed field" task, which is what a GROUP BY does in the database. Expect the ask to drop the sort once your first version works.
Take it further
Your first version sorts each word to build its signature, which costs O(k log k) per word. Now the interviewer takes the sort away. Build the same signature in O(k) using a fixed count of the 26 letters, so the whole grouping is linear in the total input size.
2

Two Sum: Complement in One Pass

EasyCommonly asked
Problem
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Exactly one valid pair exists, and you may not use the same element twice. Return the earlier index first.

Input encoding. A test case is a JSON array [nums, target]. The expected value is the two-element index array.

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. The pair 3 plus 3 is unavailable because index 0 cannot be reused.

Input: nums = [3,3], target = 6

Output: [0,1]

The two separate 3s at indices 0 and 1 add to 6.

How this uses the pattern

Keep a map from value to index. For each number, look up its complement before storing it, so the matching pair is found in a single pass.

Two Sum: Complement in One Pass

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]
The Oracle angle
Two Sum is the problem that teaches the complement trick, and it shows up at Oracle as the warm-up that proves you reach for a map before a nested loop. The double loop is O(n squared). It passes the small cases, then stalls on the large ones the editor throws at it. The signal is whether you see the one-pass version. For each number, check whether its complement is already in the map. Underneath it is any "find the pair that hits a target" task, a two-column join on a sum being the database flavor. The follow-up usually changes the memory budget or asks for every pair, not just one.
Take it further
The interviewer relaxes the index requirement and constrains memory: return the two values that sum to the target using O(1) extra space. With the indices no longer needed, sort the array and walk two pointers inward from the ends, raising the low pointer when the sum is short and lowering the high one when it overshoots.
3

Longest Consecutive Sequence: Set Membership

MediumSometimes asked
Problem
Given an unsorted array of integers nums, return the length of the longest run of consecutive integers. The run does not need to be contiguous in the array, only consecutive in value, and duplicates count once. Your solution must run in O(n) time.

Input encoding. A test case is a JSON array of integers. The expected value is the run length as a number.

Input: nums = [100,4,200,1,3,2]

Output: 4

The run 1,2,3,4 has length 4. 100 and 200 are isolated.

Input: nums = [0,3,7,2,5,8,4,6,0,1]

Output: 9

The numbers 0 through 8 are all present, so the longest run is 9. The duplicate 0 counts once.

Input: nums = []

Output: 0

No numbers, no run.

How this uses the pattern

Load the numbers into a set, then extend a run only from numbers with no left neighbor. Set membership makes each forward step O(1) and keeps the scan linear.

Longest Consecutive Sequence: Set Membership

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

Test Cases

Input: [[100,4,200,1,3,2]]Expected: 4
Input: [[0,3,7,2,5,8,4,6,0,1]]Expected: 9
Input: [[]]Expected: 0
Input: [[1,2,0,1]]Expected: 3
Input: [[9,1,4,7,3,-1,0,5,8,-1,6]]Expected: 7
The Oracle angle
This one looks like it wants a sort. It does not. Sorting is O(n log n), and Oracle pushes you to the O(n) version, which is the tell they are grading. Drop everything into a set for constant-time membership, then only start counting from a number whose predecessor is absent, so each run is walked exactly once. Interviewers often probe the complexity, because the inner while loop makes it look quadratic until you explain that only run-starts do work. Named another way it is any "longest unbroken chain" question over unordered data.
Take it further
Length is the warm-up. Now return the actual longest run of numbers, not just how long it is. Track where the winning run begins as you scan, not only its length, then rebuild the sequence from that start once the scan finishes.
The Oracle angle
The "hard" you draw in this cluster is usually hard-looking and standard. First Missing Positive is the recurring example. It rattles people because it reads like a puzzle: find the smallest missing positive integer in O(n) time and O(1) space. Turn the hashing instinct inward and use the array's own indices as the map. Place each value at the slot it belongs in, then scan for the first slot that disagrees. Say the brute force out loud first, a set of the values, then earn the in-place version when the interviewer asks for constant space. That space twist is Oracle's favorite way to escalate an easy array problem, and reaching for it unprompted is the senior signal.

Key Takeaways

  • ✓Arrays and hashing is Oracle's largest coding cluster, and the bar is easy to medium. Win it by seeing that a nested loop collapses into one hash-map pass, fast enough to clear the big test cases inside the time limit.
  • ✓Two skeletons cover most of it: a frequency map that counts in a single pass, and a lookup by key or complement that answers membership in constant time. Recognize which of the four you are looking at and you pick the structure before the details.
  • ✓Build the map by hand and keep it O(n). Oracle sometimes bans the library helper, and the editor rewards the version that compiles and passes over the clever one that does not run.
  • ✓Expect the space and sort escalations. Dropping the sort, holding O(1) extra space, and returning the sequence itself are where the loop reads your judgment. The string cluster is up next, and the sliding window is waiting there.
Had your Oracle interview?Tell us what they asked. Reviewed before it goes in, never with your name.
Oracle interview guide

Know what Oracle asks before you walk in.

19 coding · 4 system design · 18 behavioral questions

Get Premium$49 a year · 30-day money-back guarantee
Or start freeNo card.

Get their questions first.

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