K Closest Stars from a Data Stream
Updated
Problem statement
You receive a finite stream of stars in arrival order. Each row stars[i] = [starId, distance] contains a unique integer identifier and that star's nonnegative distance.
Return up to k rows with the smallest distances. Order the returned rows by increasing distance; when distances are equal, order them by increasing starId.
If k == 0, return an empty matrix. If k is greater than the number of stars, return every row in the required order.
Process the input in one pass while retaining only O(min(k, stars.length)) candidate rows before producing the ordered result.
Function
kClosestStars(stars: int[][], k: int) → int[][]Examples
Example 1
stars = [[101,50],[102,20],[103,20],[104,80]]k = 2return = [[102,20],[103,20]]Stars 102 and 103 have the two smallest distances. Their equal distances are ordered by increasing starId.
Example 2
stars = [[7,9],[3,1]]k = 5return = [[3,1],[7,9]]Because k exceeds the stream length, both stars are returned in increasing distance order.
Constraints
0 <= stars.length <= 200000.- Every row of
starshas exactly two integers:[starId, distance]. - All
starIdvalues are distinct signed 32-bit integers. 0 <= distance <= 10^9.0 <= k <= 250000.
More Google Onsite Interview questions
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Mutual-Friend RecommendationsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Tennis Court SchedulingAtlassian · PHONE SCREEN · ONSITE INTERVIEWAtlassian interview questions
- Retrieve Vectors by Cosine SimilarityHarvey · ONSITE INTERVIEWHarvey interview questions
- Meeting Rooms IISalesforce · ONSITE INTERVIEWSalesforce interview questions
- Top K Largest Values from a StreamThe D.E. Shaw Group · ONSITE INTERVIEWThe D.E. Shaw Group interview questions
- Generate Complete Inputs for a Supplied ClassifierGeneral Motors · ONSITE INTERVIEW
- Minimum Meeting Rooms Without a Sweep LineGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Top K Frequent ElementsCapgemini · ONSITE INTERVIEWCapgemini interview questions
- Select K Paired Indices for Maximum ScoreAmazon · ONSITE INTERVIEW
- Kth Largest Element in an ArrayOneTrust · ONSITE INTERVIEW