algoadvance

Design a Neighbor Sum Service that supports the following operations on an integer array:

  1. insert(idx: int, val: int)
    • Inserts val at index idx. If idx is out of bounds, do nothing.
  2. update(idx: int, val: int)
    • Updates the integer at index idx to be val. If idx is out of bounds, do nothing.
  3. sum_neighbors(idx: int) -> int
    • Returns the sum of the integer at index idx and its neighbors (i.e., idx-1, idx, and idx+1). If idx is out of bounds, return 0.

Example

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)

Clarifying Questions

  1. What should the service do if an insert operation is attempted at an index that is out of bounds?
    • Assume that nothing should happen if the index is out of bounds.
  2. What should the service do if an update operation is attempted at an index that is out of bounds?
    • Assume that nothing should happen if the index is out of bounds.
  3. What should the sum_neighbors function return if the given index has no valid neighbors?
    • It should sum the values of any existing valid neighbors only.

Strategy

Code

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

Time Complexity

Feel free to ask for any further clarifications or modifications!

Try our interview co-pilot at AlgoAdvance.com