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
- The constructor stores the array.
- Override
valueOf()to returnnums.reduce((a, b) => a + b, 0); the+operator calls it automatically. - Override
toString()to return the bracketed, comma-joined form. - The exercise targets JavaScript's type-conversion protocol: operators trigger
valueOfandSymbol.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
toStringbut notvalueOf:a + bwould concatenate strings instead of adding numbers. - Calling
reducewithout an initial value: an empty array would throw; pass 0. - Using
nums.toString()intoString: the default array stringification omits the brackets. - Storing a copy of
nums: unnecessary here; holding the reference is fine.