NeetCode #971LC-2695EasyJavaScript
← Back to All Problems

#971 · #2695 · Array Wrapper(数组包装器)

📌 Problem Statement & Constraints

Implement an ArrayWrapper class wrapping an integer array. Adding two instances with + returns the sum of all their elements, and converting an instance to a string returns the array in [1,2,3] form.

💡 Core Algorithmic Approaches

  1. The constructor stores the array.
  2. Override valueOf() to return nums.reduce((a, b) => a + b, 0); the + operator calls it automatically.
  3. Override toString() to return the bracketed, comma-joined form.
  4. The exercise targets JavaScript's type-conversion protocol: operators trigger valueOf and Symbol.toPrimitive.

💻 Benchmark Python3 Implementation

var ArrayWrapper = function(nums) {
    this.nums = nums;
};

// Called when the object takes part in a + operation
ArrayWrapper.prototype.valueOf = function() {
    return this.nums.reduce((a, b) => a + b, 0);
};

// Called when the object is converted to a string
ArrayWrapper.prototype.toString = function() {
    return "[" + this.nums.join(",") + "]";
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): summing and joining.
💾 Space Complexity
O(1): constant besides the returned string.

⚠️ Interview Pitfalls & Follow-ups

  • Overriding toString but not valueOf: a + b would concatenate strings instead of adding numbers.
  • Calling reduce without an initial value: an empty array would throw; pass 0.
  • Using nums.toString() in toString: the default array stringification omits the brackets.
  • Storing a copy of nums: unnecessary here; holding the reference is fine.