October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
The Finance Base
The Money Desk · Blog
Re:

Array Coding Problems for Interviews

A practical guide to the array coding problems that appear in interviews, including Two Sum, 3Sum, prefix sums, two pointers, in-place algorithms, and common edge cases.
From TheFinanceBase Team5 min to read
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For finance and fintech interviews, array questions are rarely about memorising one clever trick. They test whether you can turn a vague requirement into exact rules about indices, ordering, duplicates, mutation, and complexity—skills that also matter when processing prices, transactions, balances, and time-series data.

The problems below cover the patterns that appear most often: hash maps, two pointers, prefix sums, sliding windows, running extrema, sorting, and in-place rearrangement. For every problem, clarify the input constraints before choosing an algorithm.

What interviewers are testing

An interviewer may be checking whether you can:

  • Identify whether the answer concerns values, indices, or both.
  • Distinguish a contiguous subarray from an arbitrary subsequence.
  • Handle duplicate values without accidentally reusing one element.
  • Choose between brute force, sorting, hashing, prefix sums, two pointers, and dynamic programming.
  • State time complexity and auxiliary-space complexity separately.
  • Handle empty arrays, singleton arrays, negative numbers, zeros, overflow, and invalid indices.
  • Say whether your method mutates the input.

“Array” can mean a fixed-size array, a dynamic list, or an array-like container. Inserting into the middle of a contiguous array generally requires shifting later elements, even though random access is typically O(1).

The core array problems

Problem Pattern Target complexity Important trap
Two Sum Hash map O(n) expected time Do not use the same index twice
Best Time to Buy and Sell Stock Running minimum O(n) time, O(1) space Sell must occur after buying
Maximum Subarray Kadane’s algorithm O(n) time All-negative input does not return zero
Product of Array Except Self Prefix and suffix products O(n) time Division is prohibited; zeros matter
3Sum Sort plus two pointers O(n²) time Duplicate triplets must be removed
Rotate Array Reversal or cyclic replacement O(n)
time
Reduce k with k % n
Subarray Sum Equals K Prefix-sum frequency map O(n) expected time Negative values defeat a basic sliding window
Longest Consecutive Sequence Hash set O(n) expected time Only start counting at sequence beginnings
First Missing Positive In-place index placement O(n) time, O(1) space Ignore values outside 1..n
Trapping Rain Water Two pointers O(n)
time, O(1) space
Calculate trapped water, not elevation

1. Two Sum: complement lookup

Given an array and a target, return the indices of two distinct elements whose values add to the target. For example, [3, 3] and target 6 is valid because the two values occur at different indices.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Scan from left to right. For the current value x, look for target - x among previously seen values. Check the map before inserting the current value; that ordering prevents a one-element array from matching itself.

seen = {}
for i, value in enumerate(nums):
    complement = target - value
    if complement in seen:
        return [seen[complement], i]
    seen[value] = i

This uses O(n) expected time and O(n) auxiliary space. Explain that the time estimate assumes expected constant-time hash-map operations. If you sort first, you may lose the original indices unless you store value-index pairs.

2. Best Time to Buy and Sell Stock: maintain the cheapest earlier price

You may choose one buy day and one later sell day. The best result for today’s selling price is today’s price minus the minimum price seen earlier.

minimum_price = float("inf")
best_profit = 0

for price in prices:
    minimum_price = min(minimum_price, price)
    best_profit = max(best_profit, price - minimum_price)

return best_profit

A descending sequence such as [7, 6, 4, 3, 1] returns 0, not a negative number. The one-pass solution uses O(n) time and O(1) extra space.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Maximum Subarray: Kadane’s algorithm

Find the largest sum of a non-empty contiguous subarray. The word non-empty changes the answer for all-negative input: [-5, -2, -8] returns -2, not 0.

At each position, decide whether to extend the previous subarray or start a new one:

current = best = nums[0]

for value in nums[1:]:
    current = max(value, current + value)
    best = max(best, current)

return best

This is dynamic programming compressed to two variables. It runs in O(n) time and O(1) auxiliary space. If the interviewer asks for the subarray itself, retain the current start and best start/end indices.

4. Product of Array Except Self: prefix and suffix state

Return an output value for each position equal to the product of every input value except the one at that position. The standard problem requires O(n) time and disallows division.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

First place the product of all values to the left of each index into the output array. Then scan right to left while carrying the product of values to the right:

result = [1] * len(nums)

prefix = 1
for i in range(len(nums)):
    result[i] = prefix
    prefix *= nums[i]

suffix = 1
for i in range(len(nums) - 1, -1, -1):
    result[i] *= suffix
    suffix *= nums[i]

return result

The output array is excluded from the auxiliary-space count in the usual follow-up, leaving O(1) extra space. The method also handles zeros naturally. With two zeros, every result is zero. With one zero, only that zero’s position receives the product of the non-zero values.

Use a sufficiently wide numeric type for intermediate products. A guarantee that the final answers fit in 32 bits does not necessarily make every intermediate multiplication safe in every language.

5. 3Sum: sort, scan, and skip duplicates

Return distinct triplets that sum to zero. For [-1, 0, 1, 2, -1, -4], the answer is [-1, -1, 2] and [-1, 0, 1]; repeated copies are not valid output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Sort the array.
  2. Fix an index i.
  3. Use a left pointer immediately after i and a right pointer at the end.
  4. Move left when the sum is too small and right when it is too large.
  5. After finding a triplet, skip equal left and right values.

Sorting costs O(n log n), and the nested scan makes the complete solution O(n²). Sorting mutates the input unless you sort a copy, so clarify that trade-off.

6. Rotate Array: normalise the distance

To rotate right by k positions, first handle the fact that k may exceed the array length:

k = k % n

For an in-place solution, reverse the entire array, reverse the first k elements, then reverse the remaining elements. For example, rotating [1, 2, 3, 4, 5, 6, 7] right by 3 produces [5, 6, 7, 1, 2, 3, 4].

Be explicit about the empty-array case before calculating k % n; otherwise a zero-length input can cause a division-by-zero error. The reversal method takes O(n) time and O(1) auxiliary space.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

7. Subarray Sum Equals K: count prior prefix sums

Count non-empty contiguous subarrays whose sum equals k. Let the running prefix sum be p. A previous prefix sum of p - k identifies a subarray ending at the current position with sum k.

counts = {0: 1}
prefix = 0
answer = 0

for value in nums:
    prefix += value
    answer += counts.get(prefix - k, 0)
    counts[prefix] = counts.get(prefix, 0) + 1

return answer

The initial {0: 1} counts subarrays that begin at index zero. This is expected O(n) time and O(n) space.

Do not automatically replace this with a sliding window. When negative numbers are allowed, expanding a window can decrease its sum and shrinking it can increase its sum. The monotonic behaviour required by a basic sliding-window proof is absent.

8. Longest Consecutive Sequence: use sequence starts

For an unsorted array, find the length of the longest run of consecutive integers. Duplicates should not extend the run. Insert all values into a set, then begin counting only when value - 1 is absent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
values = set(nums)
best = 0

for value in values:
    if value - 1 not in values:
        length = 1
        while value + length in values:
            length += 1
        best = max(best, length)

return best

The “sequence start” condition is essential. Without it, the algorithm can rescan the same run from every element and fail the required O(n) target. The expected complexity is O(n)O(n) space.

9. First Missing Positive: map values to indices

Find the smallest positive integer absent from the array in O(n)O(1) auxiliary space. Values that matter are only 1 through n, where n is the array length.

Repeatedly place a value x at index x - 1 when 1 <= x <= n and it is not already in its correct position. Then scan for the first index i where nums[i] != i + 1. Return i + 1; if every position is correct, return n + 1.

For [3, 4, -1, 1], the result is 2. Negative values, zero, and values larger than n can be ignored during placement. This method mutates the input, which should be stated before implementation.

10. Trapping Rain Water: reason from both boundaries

Each non-negative bar has width one. Water above a position is determined by the lower of the tallest bar to its left and the tallest bar to its right, minus its own height.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A two-pointer solution keeps left_max and right_max. If the left height is lower, the left side can be resolved using the known left maximum; otherwise resolve the right side. The method handles empty and one-element arrays with a result of zero and uses O(n)O(1)

Other short problems worth practising

Array reversal

Reverse the actual elements, not merely their display order. With zero-based indexing, swap the elements at the left and right ends and move both pointers inward. An empty or singleton array is already reversed.

Array left rotation

A left rotation preserves relative order while moving the first d elements to the end. Reduce d modulo the array length. HackerRank’s Arrays preparation material also includes 2D Array - DS, New Year Chaos, Minimum Swaps 2, and Array Manipulation.

How to choose the pattern

Clue in the question Likely technique
Find a complement, frequency, or prior occurrence Hash map or hash set
Input is sorted or can be sorted safely Two pointers
Longest or shortest window with monotonic behaviour Sliding window
Exact subarray sum with negative values Prefix-sum frequency map
Each result depends on values to the left and right Prefix and suffix passes
Best result so far at every position Running extrema or dynamic programming
Required constant auxiliary space and values map to positions In-place index placement

Use the problem’s stated target rather than a memorised rule. Sorting may be perfectly acceptable for 3Sum, whose target is O(n²), but it does not meet the stated O(n) target for Longest Consecutive Sequence. Likewise, a hash set is simpler for First Missing Positive but violates its constant-space requirement.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Failure modes to test before submitting

  • Bounds: use i < n, not i <= n, and remember that the last valid index is n - 1.
  • Duplicates: Two Sum permits duplicate values at different indices; 3Sum requires duplicate triplets to be removed.
  • Empty input: test [], especially before using a first element or calculating k % n.
  • Singleton input: test [0], [1], and [-1].
  • Zeros: test product problems with no zero, one zero, and multiple zeros.
  • Negative values: test Maximum Subarray with all negatives and Subarray Sum Equals K with mixed signs.
  • Overflow: use a wider integer type where sums or products can exceed the input type.
  • Mutation: identify whether sorting, rotation, or index placement is allowed to change the caller’s array.

Language-specific traps

Python

list.sort() changes the list and returns None; sorted(nums) returns a new list. Therefore result = nums.sort() leaves result as None. Also, pop() on an empty list raises IndexError, while remove() raises ValueError if the value is absent.

JavaScript

Array.prototype.sort() mutates the array and compares elements as strings unless given a comparator:

[1, 30, 4, 21, 100000].sort();
// [1, 100000, 21, 30, 4]

nums.sort((a, b) => a - b);

Use [...nums].sort((a, b) => a - b) when the input must remain unchanged. Modern JavaScript also provides toSorted() for a non-mutating sorted copy. Do not promise a particular sort() time complexity based only on the language specification.

Java and C++

For a Java array, use array.length, not array.length(). In portable standard C++, avoid variable-length stack arrays; use std::vector<int> when the runtime determines the size.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical preparation sequence

  1. Start with Two Sum, stock profit, reversal, and rotation to practise indexing and one-pass state.
  2. Add Maximum Subarray and Product of Array Except Self to learn compressed dynamic programming and prefix/suffix passes.
  3. Practise 3Sum and trapping water to build two-pointer intuition.
  4. Work through Subarray Sum Equals K and Longest Consecutive Sequence with explicit complexity proofs.
  5. Finish with First Missing Positive, where the space constraint determines the entire approach.
  6. For HackerRank, use Log in → Prepare → Prep Kits, then open the Arrays Interview Questions collection.

For each solution, explain the invariant in one sentence. Examples: “The map contains only values from earlier indices,” or “Every value before the left pointer has already been resolved.” That explanation is often more valuable in an interview than typing the final loop quickly.

FAQ

Which array coding problems should I practise first for an interview?

Start with Two Sum, Best Time to Buy and Sell Stock, Maximum Subarray, array reversal, and rotation. Then practise Product of Array Except Self, 3Sum, Subarray Sum Equals K, Longest Consecutive Sequence, and First Missing Positive.

Why does a sliding window fail for some subarray-sum problems?

A basic sliding window depends on the sum changing predictably as the window expands or contracts. Negative numbers break that monotonic behaviour, so exact-sum counting with mixed positive and negative values generally needs prefix sums and a frequency map.

What is the difference between auxiliary space and output space?

Auxiliary space is temporary memory used beyond the required result. In Product of Array Except Self, the required output array is commonly excluded from the auxiliary-space calculation, allowing an O(1)-extra-space solution.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should array interview solutions mutate the input?

Only when the problem permits or requires it. In-place rotation and First Missing Positive normally mutate the array, while sorting for 3Sum may also mutate it unless you sort a copy. State the choice and its consequence before coding.

The Bottom Line

Strong array interview performance comes from matching the requirement to the pattern: hash maps for complements and counts, two pointers for ordered or bidirectional scans, prefix sums for exact subarray totals, prefix/suffix state for left-and-right dependencies, and in-place index mapping when memory is constrained. Before presenting the solution, verify duplicates, boundaries, negative numbers, zeros, overflow, complexity, and input mutation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More post from the Money Desk

  1. The Money DeskBlogTheFinanceBase09 OCT 267 minMortgage Escrow FAQs: Taxes, Insurance, Shortages, and Refunds
  2. The Money DeskBlogTheFinanceBase09 OCT 265 minHow Mortgage Escrow Accounts Work and What Homeowners Pay For
  3. The Money DeskBlogTheFinanceBase09 OCT 265 minHow to Read a Stock Chart, Volume and Market-Cap Data
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.