Design a Neighbor Sum Service that supports the following operations on an integer array:
val
at index idx
. If idx
is out of bounds, do nothing.idx
to be val
. If idx
is out of bounds, do nothing.idx
and its neighbors (i.e., idx-1
, idx
, and idx+1
). If idx
is out of bounds, return 0.nss = NeighborSumService([1, 2, 3, 4])
nss.insert(1, 5) # Now, the array is [1, 5, 2, 3, 4]
nss.update(2, 8) # Now, the array is [1, 5, 8, 3, 4]
print(nss.sum_neighbors(2)) # Returns 16 (5 + 8 + 3)
print(nss.sum_neighbors(4)) # Returns 7 (3 + 4)
insert
operation is attempted at an index that is out of bounds?
update
operation is attempted at an index that is out of bounds?
sum_neighbors
function return if the given index has no valid neighbors?
sum_neighbors
, check bounds before accessing the array to avoid out-of-bounds errors.class NeighborSumService:
def __init__(self, initial_array):
# Initialize with the given integer array
self.array = initial_array
def insert(self, idx, val):
# Check index is within bounds
if 0 <= idx <= len(self.array):
self.array.insert(idx, val)
def update(self, idx, val):
# Check index is within bounds
if 0 <= idx < len(self.array):
self.array[idx] = val
def sum_neighbors(self, idx):
if 0 <= idx < len(self.array):
neighbor_sum = 0
# Include value at idx
neighbor_sum += self.array[idx]
# Include value at idx - 1 if valid
if idx - 1 >= 0:
neighbor_sum += self.array[idx - 1]
# Include value at idx + 1 if valid
if idx + 1 < len(self.array):
neighbor_sum += self.array[idx + 1]
return neighbor_sum
# If idx is out of bounds, return 0
return 0
insert(idx: int, val: int)
:
n
is the length of the array, due to the potential reallocation of elements.update(idx: int, val: int)
:
sum_neighbors(idx: int) -> int
:
Feel free to ask for any further clarifications or modifications!
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?