We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Wrapper

Difficulty: Easy


Problem Description

Create a class ArrayWrapper that accepts an array of integers in its constructor. This class should have two features:

  1. When two instances of this class are added together with the + operator, the resulting value is the sum of all the elements in both arrays.
  2. When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

Key Insights

  • The class needs to implement operator overloading for addition to handle the summation of two ArrayWrapper instances.
  • The class should also implement a method to return a string representation of the array in a specified format.
  • The solution requires careful handling of edge cases, such as empty arrays.

Space and Time Complexity

Time Complexity: O(n), where n is the total number of elements in both arrays being summed. Space Complexity: O(1) for the sum operation since we are only using a constant amount of space, but O(m) for the string representation where m is the number of elements in the array.


Solution

To solve the problem, we will create a class ArrayWrapper. This class will:

  1. Store the input array in its constructor.
  2. Implement the __add__ method to allow the use of the + operator. This method will iterate through both arrays and return the sum of their elements.
  3. Implement the __str__ method to format the array as a string in the required format. This method will convert the array to a string, joining the elements with commas and surrounding them with brackets.

Code Solutions

class ArrayWrapper:
    def __init__(self, arr):
        self.arr = arr  # Store the input array

    def __add__(self, other):
        # Calculate the sum of both arrays
        return sum(self.arr) + sum(other.arr)

    def __str__(self):
        # Return the string representation of the array
        return f"[{','.join(map(str, self.arr))}]"
← Back to All Questions