Problem

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

  • 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.
  • When the String() function is called on the instance, it will return a comma separated string surrounded by brackets. For example, [1,2,3].

Examples

Example 1

1
2
3
4
5
6
Input: nums = [[1,2],[3,4]], operation = "Add"
Output: 10
Explanation:
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
obj1 + obj2; // 10

Example 2

1
2
3
4
5
Input: nums = [[23,98,42,70]], operation = "String"
Output: "[23,98,42,70]"
Explanation:
const obj = new ArrayWrapper([23,98,42,70]);
String(obj); // "[23,98,42,70]"

Example 3

1
2
3
4
5
6
Input: nums = [[],[]], operation = "Add"
Output: 0
Explanation:
const obj1 = new ArrayWrapper([]);
const obj2 = new ArrayWrapper([]);
obj1 + obj2; // 0

Constraints

  • 0 <= nums.length <= 1000
  • 0 <= nums[i] <= 1000
  • Note: nums is the array passed to the constructor

Solution

Method 1 – Operator Overloading via valueOf and toString

Intuition

We want to make a class that acts like a number when used with + and like an array string when used with String(). In JavaScript and TypeScript, this is done by implementing valueOf (for arithmetic) and toString (for string conversion).

Approach

  1. Store the input array as a property.
  2. Implement valueOf() to return the sum of the array, so + uses this value.
  3. Implement toString() to return the array as a comma-separated string in brackets.
  4. Handle empty arrays gracefully.
JavaScript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class ArrayWrapper {
    constructor(nums) {
        this.arr = nums;
    }
    valueOf() {
        return this.arr.reduce((ans, n) => ans + n, 0);
    }
    toString() {
        return `[${this.arr.join(",")}]`;
    }
}
TypeScript
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class ArrayWrapper {
    private arr: number[];
    constructor(nums: number[]) {
        this.arr = nums;
    }
    valueOf(): number {
        return this.arr.reduce((ans, n) => ans + n, 0);
    }
    toString(): string {
        return `[${this.arr.join(",")}]`;
    }
}

Complexity

  • ⏰ Time complexity: O(N) per operation, where N is the number of elements in the array.
  • 🧺 Space complexity: O(N) for string conversion.