C3 AICodingFree preview
Star Sum: Best k-Star Sum in a Graph
HackerRank OA coding task: given an undirected graph with node values and an integer k, return the maximum sum of a star subgraph (a center plus at most k neighbors). Function bestSumKStar(g_nodes, g_from, g_to, values, k); up to 1e5 nodes/edges, values in [-1000, 1000], k may be 0.
SWE
graph
Frequency
Single report
Last asked
2026-10-04
Stage
oa
Problem
HackerRank coding task, titled Solutions Engineering – Star Sum.
Given an integer k and an undirected graph G with g_nodes nodes and g_edges edges, where node i has value values[i]:
- A star graph is a center node plus some of its neighbors (the "arms").
- A k-star is a non-empty subgraph of
Gthat is a star graph with at mostkarms. Zero arms is allowed, so a single node on its own is a valid k-star. - Return the sum of the k-star with the largest sum among all k-stars.
Complete the function bestSumKStar:
int bestSumKStar(int g_nodes, int[] g_from, int[] g_to, int[] values, int k)g_nodes— number of nodes in the graph.g_from[i],g_to[i]— endpoints of the i-th edge.values[i]— value of nodei.k— maximum number of arms in the star.
Constraints
2 ≤ g_nodes ≤ 10^51 ≤ g_edges ≤ 10^50 ≤ g_from[i], g_to[i] ≤ n - 10 ≤ k ≤ 10^5-10^3 ≤ values[i] ≤ 10^3- No self-loops; at most one edge between any pair of vertices.
Examples
g_nodes=4, edges 0-1,0-2,1-3, values=[5,-2,4,3], k=2 -> 9Center 0 takes only neighbor 2 (5 + 4 = 9); neighbor 1 has a negative value, so adding it would lower the sum even though a second arm is allowed.
Hints
Pitfalls
- "At most
karms": a star does not have to use allkarms, andkcan be0, in which case a star is just a single node. - Node values can be negative, but the k-star must be non-empty, so the answer can itself be negative. Initialize the running best to negative infinity (or the first node's value), not
0. - Taking the top
kneighbors without first dropping non-positive ones gives wrong answers whenever a node has fewer thankpositive neighbors. - Edges are undirected: add each endpoint to the other's list.
- With up to 10^5 nodes and edges, anything that enumerates subsets of neighbors will time out; aim for near-linear work per node degree.
Talking Points
- Fixing the center makes the arms independent, so a greedy pick of the largest positive neighbors is optimal.
- The lone-center case is what handles all-negative neighborhoods; no special-casing is needed.
- For high-degree nodes, mention swapping the full sort for a size-
kheap.
Preparation
- Implement
bestSumKStarend to end from the rawg_from/g_toedge arrays, including building the adjacency list. - Hand-test the boundary cases from the constraints:
k = 0, all-negative values, and a node whose degree exceedsk. - Time yourself on the full HackerRank flow (parse input, solve, print) so the second coding problem and the multiple-choice section still fit in the session.
Was this article helpful?
Comments
Sign in to join the discussion
Loading...
