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

Number: 2805

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Design a class named ArrayWrapper that accepts an array of integers in its constructor. This class must support two primary features:

  • When two instances are added together with the + operator, the result should be the sum of all the integers contained in both arrays.
  • When the String() function is called on an instance, it should return a string representation of the array in the format "[a,b,c]".

Key Insights

  • The core of the problem is overloading behaviors: addition (operator overloading in languages that support it) and conversion to string.
  • In languages without direct operator overloading (e.g., JavaScript and Java), appropriate techniques (valueOf, toString, or helper methods) must be employed.
  • Internally, the sum is computed by iterating over each element in the array.
  • For the string conversion, join the array elements with commas and wrap the result in square brackets.

Space and Time Complexity

Time Complexity: O(n) for summing up the numbers in the array (where n is the length of the array).
Space Complexity: O(n) for storing the array.


Solution

We implement the ArrayWrapper class with an internal array storage. For the addition operation, in languages that support operator overloading (Python, C++), we define an overloaded operator that calculates the sum of both arrays. In JavaScript, we use the valueOf method to return the sum when used with the + operator. In Java, operator overloading is not allowed, so a helper method (e.g., add) is provided to mimic this behavior. The toString method (or its equivalent) converts the internal array into the desired string format by joining the elements with commas and enclosing them in brackets.


Code Solutions

# Python Implementation of ArrayWrapper

class ArrayWrapper:
    def __init__(self, nums):
        # Initialize the ArrayWrapper with the given list of integers.
        self.nums = nums

    def __add__(self, other):
        # When two ArrayWrapper objects are added, return the sum of all integers in both arrays.
        return sum(self.nums) + sum(other.nums)
    
    def __str__(self):
        # Return a string representation in the format "[elem1,elem2,...]".
        return "[" + ",".join(str(num) for num in self.nums) + "]"

# Example usage:
# obj1 = ArrayWrapper([1,2])
# obj2 = ArrayWrapper([3,4])
# print(obj1 + obj2)    # Outputs: 10
# print(str(obj1))      # Outputs: "[1,2]"
← Back to All Questions