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.
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.
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:
i - k >= 0, is nums[i] > nums[i - k]?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.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.i - k or i + k are valid indices before accessing the array.>= instead of > (as per the "strictly greater" rule).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.