← Google Interview Insights

Google·Software Engineer·Onsite - Coding / Algorithms·Intermediate

IntermediatePrefer not to say
Jul 2026

Summary

Google SWE coding round, one question on subarray sums. Pretty standard algorithmic problem but the constraints are wide enough that a naive O(n^2) solution won't cut it.

Questions Asked (1)

Q1

Given an integer array and a target value k, find the total number of contiguous subarrays whose elements sum to k.

Algorithms & Data Structures
Author's notes

My first instinct was the brute force nested loop and I actually started coding it before catching myself.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying the problem constraints (e.g., array size, element types, whether negative numbers are allowed) and then propose an efficient solution using a hash map to store prefix sums. Explain that this approach reduces the time complexity from O(n^2) to O(n) by leveraging the relationship between prefix sums and the target sum.

Pro tip: Mention edge cases like empty array, all zeros, and negative numbers, and discuss how the prefix sum approach handles them. Also, briefly compare with the brute-force method to highlight the efficiency gain.

1. Clarify the problem

Ask about constraints: array size, element range, whether negative numbers are allowed, and if the subarrays must be non-empty. Confirm the expected return type (integer count).

2. Discuss brute-force approach

Mention that a naive solution would check all subarrays, leading to O(n^2) time complexity, which is inefficient for large inputs.

3. Introduce prefix sum with hash map

Explain that by keeping a running sum and using a hash map to store the frequency of each prefix sum, we can find the number of subarrays ending at each index that sum to k in O(1) average time.

4. Walk through the algorithm

Initialize a hash map with {0:1} to handle subarrays starting from index 0. Iterate through the array, update the running sum, and for each element, add the count of (running sum - k) from the map to the result, then update the map with the current running sum.

5. Analyze complexity and edge cases

State that time complexity is O(n) and space complexity is O(n) in the worst case. Discuss edge cases like empty array, k=0, and negative numbers, and confirm the algorithm handles them correctly.

Key Points to Mention

  • Prefix sum concept: cumulative sum from start to current index.
  • Hash map to store frequency of prefix sums for O(1) lookups.
  • Handling of negative numbers and zeros: prefix sums can repeat, and the map counts frequencies.
  • Initialization of hash map with {0:1} to account for subarrays starting at index 0.
  • Time and space complexity: O(n) time, O(n) space.
  • Comparison with brute-force O(n^2) approach to highlight efficiency.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.