Arrays and hashing coding interview questions 14 questions in 4 chapters

  1. 01Hash map and set lookups5 questions
  2. 02Single-pass array scans3 questions
  3. 03Prefix sums3 questions
  4. 04In-place index tricks3 questions

Hash map and set lookups

Complement lookup, membership checks, counting and grouping with HashMap and HashSet.

  • 1.1 Two Sum Easy 3 min

    I walk the array once and keep a HashMap from value to index. For each number I check whether target minus that number is already in the map. If it is, I return both indices, and if not, I store the current number. That is linear time and linear space, compared with the quadratic brute force over all pairs.

    Read the full answer
  • 1.2 Contains Duplicate Easy 2 min

    I add every number to a HashSet. Set add returns false when the element is already there, so the first false means there is a duplicate and I return true right away. That is linear time and linear space. If memory matters more, I can sort and compare neighbours in n log n time.

    Read the full answer
  • 1.3 Valid Anagram Easy 3 min

    Two strings are anagrams when every character appears the same number of times in both. For lowercase English letters I use an int array of 26: increment for the first string, decrement for the second, and check that everything is back to zero. I return false early if the lengths differ. For full Unicode I would switch to a HashMap of code points.

    Read the full answer
  • 1.4 Group Anagrams Medium 3 min

    I give every word a canonical key that is the same for all its anagrams, then group words by that key in a HashMap. The simplest key is the word's sorted characters. A faster key is the 26 letter counts joined into a string, which avoids sorting each word. computeIfAbsent creates each group the first time I see its key.

    Read the full answer
  • 1.5 Longest Consecutive Sequence Medium 3 min

    I put all numbers in a HashSet. Then I only start counting from numbers that begin a run, meaning x minus 1 is not in the set, and walk upward while x plus 1 exists. Each number is visited at most twice, so it is linear time even though there is a nested loop. Sorting would also work, but in n log n.

    Read the full answer

Single-pass array scans

Running minimum, prefix and suffix products, and signed running products.

  • 2.1 Best Time to Buy and Sell Stock Easy 2 min

    I scan prices once while tracking the lowest price so far. At each day the best profit if I sell today is price minus that minimum, and I keep the maximum of those. If prices only go down, the answer stays zero because I am allowed not to trade. That is linear time and constant space.

    Read the full answer
  • 2.2 Product of Array Except Self Medium 3 min

    For each index the answer is the product of everything to its left times everything to its right. I fill the output with left products in one pass, then walk back from the right with a running right product and multiply it in. No division, so zeros are not a problem, and apart from the output it is constant extra space.

    Read the full answer
  • 2.3 Maximum Product Subarray Medium 2 min

    It looks like Kadane, but a negative number can turn the smallest product into the largest. So at each element I track both the maximum and the minimum product ending here. The new max is the largest of the element, element times old max and element times old min, and symmetrically for the min. One pass, constant space.

    Read the full answer

Prefix sums

Precomputed running totals for range queries and counting subarrays with a target sum.

  • 3.1 Range Sum Query - Immutable Easy 2 min

    I precompute a prefix array where prefix of i plus one is the sum of the first i plus one elements. Then the sum from left to right is prefix of right plus one minus prefix of left, which is constant time per query after linear preprocessing. The extra leading zero removes the special case for left equals zero.

    Read the full answer
  • 3.2 Subarray Sum Equals K Medium 3 min

    I keep a running prefix sum and a HashMap counting how many times each prefix sum has appeared, starting with zero once. At each index, the number of subarrays ending here with sum k equals how many earlier prefixes equal current sum minus k. A sliding window does not work here because values can be negative.

    Read the full answer
  • 3.3 Continuous Subarray Sum Medium 3 min

    A subarray sum is a multiple of k exactly when two prefix sums have the same remainder mod k. So I store the first index where each remainder appeared, seeding remainder zero at index minus one. If I see a remainder again at least two positions later, the subarray in between has length two or more and a sum divisible by k.

    Read the full answer

In-place index tricks

Using the value range 0..n or 1..n to find missing numbers with constant extra space.

  • 4.1 Missing Number Easy 2 min

    The array holds n distinct numbers from zero to n with one missing. XOR every index from zero to n with every value; equal numbers cancel, so what remains is the missing one. The sum formula also works, but XOR cannot overflow. Both are linear time and constant space.

    Read the full answer
  • 4.2 Find All Numbers Disappeared in an Array Easy 3 min

    Values are between one and n, so each value can point at an index. For every value I flip the number at index value minus one to negative. Afterwards, any index that is still positive means that value plus one never appeared. That is linear time and no extra space apart from the output, though it temporarily modifies the input.

    Read the full answer
  • 4.3 First Missing Positive Hard 3 min

    The answer is always between one and n plus one, so only values in that range matter. I do a cyclic sort, swapping each value v in one to n into index v minus one until every slot holds its own number or a value I can ignore. Then the first index i where nums of i is not i plus one gives the answer, otherwise n plus one. Linear time, constant space.

    Read the full answer