Google Interview experience
1 round over 2 weeks. No offer, meh experience.
I was asked a basic DSA question during the interview and was encouraged to further optimize my solution. The interviewer was friendly and guided me through different stages of the problem. Although there were two interview rounds in the selection process, I was unable to pass the first one.
Problem:
I was given an array of integers and asked to find a pair of indices i and j where the sum of the elements between these indices (excluding the elements at i and j) is as large as possible, and the elements at i and j must be the same.
Example input:
array = [4, 2, 1, 4, 3, 2, 4]Example output:
The maximum sum of elements between any valid pairs is 12 (between indices 0 and 6).
Possible optimal solution (not the one provided during the interview):
import java.util.HashMap;
import java.util.Map;
public class MaxSumBetweenEqualPairs {
public static int findMaxSum(int[] array) {
int n = array.length;
int[] prefixSum = new int[n + 1]; // Prefix sum array, 1 extra element for easier indexing
// Compute prefix sums
for (int i = 0; i < n; i++) {
prefixSum[i + 1] = prefixSum[i] + array[i];
}
// Map to track last occurrence and max sum seen so far for each value
Map<Integer, Integer> lastOccurrence = new HashMap<>();
int maxSum = Integer.MIN_VALUE;
// Iterate over the array
for (int i = 0; i < n; i++) {
int value = array[i];
// Check if the value has been seen before
if (lastOccurrence.containsKey(value)) {
// Get the last index where this value was seen
int lastIndex = lastOccurrence.get(value);
// Calculate the sum of elements between lastIndex and current index i
int currentSum = prefixSum[i] - prefixSum[lastIndex + 1];
// Update maxSum if the currentSum is larger
maxSum = Math.max(maxSum, currentSum);
}
// Update the last occurrence of the value to the current index
lastOccurrence.put(value, i);
}
// Return 0 if no valid pairs were found
return maxSum == Integer.MIN_VALUE ? 0 : maxSum;
}
public static void main(String[] args) {
int[] array = {4, 2, 1, 4, 3, 2, 4};
System.out.println(findMaxSum(array)); // Output: 12
}
}Time & Space Complexity:
O(n) since we only make a single pass through the array and use prefix sums to efficiently compute subarray sums.
O(n) for the prefix sums and the hash map
Know someone interviewing at Google? Pass it on.
Same company, different candidates.
Share yours while it’s fresh. It takes five minutes, it’s anonymous, and it will help future candidates.