Leetcode 3242. Design Neighbor Sum Service
You have to design a service to calculate a neighbor sum in a streaming fashion. Implement the NeighborSumService
class which contains the following methods:
NeighborSumService()
: Initializes the object, no data needs to be preserved here.void addNum(int num)
: Adds a number to the data structure.int getSum(int index)
: Returns the sum of the numbers located at positions ‘index’, ‘index-1’, and ‘index+1’ if they exist, otherwise returns the sum of the existing neighbors (e.g., if index-1
is out of bounds, it’s not included in the sum).index
provided in getSum
has no elements around it or out of bounds?
A: Only valid neighbors should be summed. If no such neighbors exist (e.g., empty structure or inappropriate indices), return 0.import java.util.ArrayList;
import java.util.List;
public class NeighborSumService {
private List<Integer> nums;
public NeighborSumService() {
this.nums = new ArrayList<>();
}
public void addNum(int num) {
this.nums.add(num);
}
public int getSum(int index) {
int sum = 0;
if (index >= 0 && index < nums.size()) {
sum += nums.get(index);
}
if (index > 0 && index - 1 < nums.size()) {
sum += nums.get(index - 1);
}
if (index + 1 >= 0 && index + 1 < nums.size()) {
sum += nums.get(index + 1);
}
return sum;
}
public static void main(String[] args) {
NeighborSumService service = new NeighborSumService();
service.addNum(1);
service.addNum(2);
service.addNum(3);
System.out.println(service.getSum(1)); // Output should be 6 (1 + 2 + 3)
System.out.println(service.getSum(0)); // Output should be 3 (1 + 2)
System.out.println(service.getSum(2)); // Output should be 5 (3 + 2)
}
}
NeighborSumService
): Initialize a list to store the stream of numbers.addNum
): Simply append the number to the list.getSum
):
index
, index-1
, and index+1
if they exist within the list boundaries.addNum(int num)
:
getSum(int index)
:
The solution efficiently handles the requirements of the problem using an ArrayList, ensuring constant time operations for both adding numbers and retrieving the neighbor sums.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?