← Google Interview Insights

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

Intermediate
May 2026

Summary

Google SWE coding round, one algorithmic problem about sorting an almost-sorted array. Pretty focused session, no fluff.

Questions Asked (1)

Q1

Given an array where each element is at most K positions away from its sorted position, sort the array efficiently.

Algorithms & Data Structures
Author's notes

My first instinct was to just throw a standard sort at it and call it a day, but that felt too easy for Google.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Recognize that the array is 'k-sorted' and use a min-heap of size k+1 to efficiently extract the smallest element at each step. Iterate through the array, maintaining the heap, and place the extracted minimum into the sorted output. This achieves O(n log k) time and O(k) space, which is optimal for this problem.

Pro tip: Mention that for small k, this is nearly linear, and for k = n, it degrades to O(n log n) which is optimal for general sorting. Also, note that the heap approach is stable if needed by storing indices, but stability isn't required here.

1. Understand the problem

Clarify that each element is at most K positions away from its sorted position, meaning the array is 'k-sorted'. This implies that the smallest element among the first K+1 elements must be the global minimum.

2. Choose the right data structure

Use a min-heap to efficiently retrieve the minimum element among a sliding window of size K+1. The heap will contain at most K+1 elements at any time.

3. Algorithm design

Initialize the heap with the first K+1 elements. Then, for each position from 0 to n-1, extract the minimum from the heap and place it in the sorted array. If there are remaining elements, add the next element from the array to the heap.

4. Complexity analysis

Building the initial heap takes O(K) time. Each of the n extract-min and insert operations takes O(log K) time, leading to O(n log K) overall. Space is O(K) for the heap.

5. Edge cases and optimizations

Handle cases where K >= n (heap size n) or K = 0 (already sorted). For small K, the algorithm is nearly linear. Mention that if K is large, other sorting algorithms might be more suitable.

Key Points to Mention

  • Definition of k-sorted array and its implication on the position of the minimum element.
  • Use of a min-heap (priority queue) to maintain the sliding window of size K+1.
  • Time complexity O(n log K) and space complexity O(K).
  • Comparison with other approaches: insertion sort O(nK), quickselect-based, or full sort O(n log n).
  • Handling of edge cases: K=0, K>=n, and empty array.
  • Potential optimization: if K is small, the log K factor is negligible, making it almost linear.

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