Magicsheet logo

Sum of Good Numbers

Easy
100%
Updated 8/1/2025

Asked by 2 Companies

Topics

Sum of Good Numbers

What is this problem about?

The "Sum of Good Numbers" problem defines a "good number" in an array based on its neighbors at a specific distance k. An element nums[i] is considered "good" if it is strictly greater than nums[i - k] (if it exists) and strictly greater than nums[i + k] (if it exists). Your task is to find all such "good numbers" in the array and return their sum.

Why is this asked in interviews?

This "Easy" level question, seen at Google and Bcg, tests basic array traversal and boundary condition handling. It evaluates whether a candidate can write clean, readable code while correctly checking for index existence. It's a simple test of "coding hygiene"—ensuring indices don't go out of bounds and logic is straightforward.

Algorithmic pattern used

The pattern is a simple "Linear Scan with Conditional Checks." You iterate through the array once from i = 0 to n-1. For each i, you check two conditions:

  1. If i - k >= 0, is nums[i] > nums[i - k]?
  2. If i + k < n, is nums[i] > nums[i + k]? If both checks (for those neighbors that exist) pass, you add nums[i] to your total.

Example explanation

Array: [1, 3, 2, 1], k = 2.

  • i = 0: Left neighbor 0-2 (none), Right neighbor 0+2 (value 2). 1 is not > 2. Not good.
  • i = 1: Left neighbor 1-2 (none), Right neighbor 1+2 (value 1). 3 > 1. Good! Sum = 3.
  • i = 2: Left neighbor 2-2 (value 1), Right neighbor 2+2 (none). 2 > 1. Good! Sum = 3 + 2 = 5.
  • i = 3: Left neighbor 3-2 (value 3), Right neighbor 3+2 (none). 1 is not > 3. Not good. Result = 5.

Common mistakes candidates make

  1. Index Out of Bounds: Forgetting to check if i - k or i + k are valid indices before accessing the array.
  2. Strict Inequality: Using >= instead of > (as per the "strictly greater" rule).
  3. Missing a neighbor: Only checking the left neighbor or only the right one.

Interview preparation tip

For "Easy" problems, focus on edge cases. What happens if k is larger than the array length? What if the array has only one element? Writing code that naturally handles these without multiple nested if statements is a sign of a proficient developer.

Similar Questions