Array Wrapper solution and explanation
9 more videos on this problem
Array Wrapper - Leetcode 2695 - JavaScript 30-Day ChallengeNeetCodeIO · 5:32 · 5K views
Array Wrapper | Leetcode 2695 | Classes | 30 Days of JavaScript #javascript #leetcodeLearn With Chirag · 11:08 · 1K views
LeetCode 2695. Array Wrapper. ENКанал про вирішення ЛітКод Українською · 7:33 · 171 views
2695. Array Wrapper - Day 28/30 Leetcode Javascript ChallengeProgramming Live with Larry · 6:47 · 152 views
Array Wrapper - LeetCode 2695 - JavaScript - JS 30 Day Challenge Day 27Alpha-Code · 8:47 · 149 views
Day 28. LeetCode 2695. Array Wrapper. Daily JS challengeКанал про вирішення ЛітКод Українською · 7:47 · 136 views
#Leetcode 2695 Array Wrapper 🚀 Day 29 👨💻 30Days of JavaScript Challenge LeetCodeRajat Talesra · 4:34 · 87 views
Leetcode 2695: Array Wrapper (Easy) | Typescript (Español)Eliaz Bobadilla (Programación) · 7:15 · 54 views
2695. Array Wrapper | JavaScript Class MagicCodeCrafting with Vishnu · 4:09 · 50 views
2695 Array Wrapper | Three Solutions | LeetCode | Data StructuresO(1) Software Network · 58:37 · 46 views
The 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].
Example 1:
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:
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:
Input: nums = [[],[]], operation = "Add" Output: 0 Explanation: const obj1 = new ArrayWrapper([]); const obj2 = new ArrayWrapper([]); obj1 + obj2; // 0
Constraints:
0 <= nums.length <= 10000 <= nums[i] <= 1000Note: nums is the array passed to the constructor
Approach overview
Problem Overview: You design a wrapper class around an integer array. When two wrapper objects are added using +, the result should be the sum of all elements from both arrays. Converting the object to a string should produce the array in bracket format like [1,2,3].
Approach 1: Operator Overloading to Implement Addition and String Conversion (O(n) time, O(1) space)
The wrapper stores the input array internally and relies on language features that customize how objects behave in arithmetic and string contexts. In JavaScript, implementing valueOf() allows the runtime to convert the object into a primitive number when the + operator is used. The method simply iterates through the stored array and computes the sum using a loop or reduce. For printing, toString() returns the bracketed representation by joining elements with commas.
Each addition triggers a linear scan of the array, so the time complexity is O(n). The string conversion also requires iterating through the array to build the formatted output, again O(n). No extra data structures are needed beyond the stored array, giving O(1) auxiliary space. This approach directly leverages language-level operator behavior, making the implementation concise and idiomatic for problems involving object-oriented programming and operator overloading.
Approach 2: Interface / Method Implementation for Addition and String Conversion (O(n) time, O(1) space)
Languages like Python and Java expose explicit hooks for customizing arithmetic and string behavior. In Python, implementing __add__ defines how two objects combine when the + operator is used. The method iterates through both internal arrays (or sums their values) and returns the total. The __str__ method formats the array into the required bracket string. Java can achieve the same behavior by implementing equivalent methods or interfaces and defining custom logic for summation and printing.
The core idea remains the same: store the array once and compute its total when addition occurs. The summation requires iterating through elements, giving O(n) time, while formatting the array string also takes O(n). Memory usage stays O(1) beyond the input array. This approach is language-agnostic and highlights how operator behavior can be customized through method overrides in object-oriented programming environments.
Recommended for interviews: The operator overloading approach is the expected solution because the problem explicitly tests understanding of how objects interact with operators and string conversion. Demonstrating both numeric conversion (valueOf or __add__) and string formatting (toString or __str__) shows solid knowledge of language internals. A brute-force mindset—iterating to compute the sum—is acceptable here since the operation is inherently linear.
Approach 1: Operator Overloading to Implement Addition and String Conversion
This approach leverages operator overloading (or language-specific methods) to define how instances of ArrayWrapper behave when used with the '+' operator and the String conversion function. We'll override/add appropriate methods to customize these operations:
- Addition: We'll implement the addition operation for the '+' operator to sum the elements in two
ArrayWrapperinstances. - String Conversion: We'll override the method responsible for converting an object to a string, to provide the correct format.
class ArrayWrapper:
def __init__(self, nums):
self.nums = nums
def __add__(self, other):
return sum(self.nums) + sum(other.nums)
def __str__(self):
return str(self.nums)
# Usage Example
obj1 = ArrayWrapper([1,2])
obj2 = ArrayWrapper([3,4])
print(obj1 + obj2) # Output: 10
print(str(obj1)) # Output: [1, 2]import java.util.Arrays;
class ArrayWrapper {
private int[] nums;
public ArrayWrapper(int[] nums) {
this.nums = nums;
}
public int add(ArrayWrapper other) {
return Arrays.stream(this.nums).sum() + Arrays.stream(other.nums).sum();
}
@Override
public String toString() {
return Arrays.toString(nums);
}
}
// Usage Example
ArrayWrapper obj1 = new ArrayWrapper(new int[]{1,2});
ArrayWrapper obj2 = new ArrayWrapper(new int[]{3,4});
System.out.println(obj1.add(obj2)); // Output: 10
System.out.println(obj1.toString()); // Output: [1, 2]#include <iostream>
#include <vector>
#include <numeric>
#include <sstream>
class ArrayWrapper {
std::vector<int> nums;
public:
ArrayWrapper(std::vector<int> nums) : nums(nums) {}
int operator+(const ArrayWrapper& other) {
return std::accumulate(this->nums.begin(), this->nums.end(), 0) +
std::accumulate(other.nums.begin(), other.nums.end(), 0);
}
friend std::ostream& operator<<(std::ostream& os, const ArrayWrapper& aw) {
os << "[";
for(size_t i = 0; i < aw.nums.size(); ++i) {
os << aw.nums[i];
if (i != aw.nums.size() - 1) os << ",";
}
os << "]";
return os;
}
};
// Usage Example
int main() {
ArrayWrapper obj1({1, 2});
ArrayWrapper obj2({3, 4});
std::cout << (obj1 + obj2) << std::endl; // Output: 10
std::cout << obj1 << std::endl; // Output: [1,2]
return 0;
}class ArrayWrapper {
constructor(nums) {
this.nums = nums;
}
valueOf() {
return this.nums.reduce((a, b) => a + b, 0);
}
toString() {
return `[${this.nums.join(',')}]`;
}
}
// Usage Example
const obj1 = new ArrayWrapper([1,2]);
const obj2 = new ArrayWrapper([3,4]);
console.log(obj1 + obj2); // Output: 10
console.log(String(obj1)); // Output: [1,2]#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* nums;
int length;
} ArrayWrapper;
ArrayWrapper createArrayWrapper(int* nums, int length) {
ArrayWrapper aw;
aw.nums = nums;
aw.length = length;
return aw;
}
int addArrays(ArrayWrapper a, ArrayWrapper b) {
int sum = 0;
for (int i = 0; i < a.length; i++) sum += a.nums[i];
for (int i = 0; i < b.length; i++) sum += b.nums[i];
return sum;
}
char* arrayToString(ArrayWrapper a) {
char* buffer = malloc((a.length * 4 + 2) * sizeof(char)); // Maximum 4 chars per number + brackets
sprintf(buffer, "[");
for(int i = 0; i < a.length; i++) {
char temp[5];
sprintf(temp, "%d", a.nums[i]);
strcat(buffer, temp);
if (i < a.length - 1) strcat(buffer, ",");
}
strcat(buffer, "]");
return buffer;
}
// Usage Example
int main() {
int arr1[] = {1, 2};
int arr2[] = {3, 4};
ArrayWrapper obj1 = createArrayWrapper(arr1, 2);
ArrayWrapper obj2 = createArrayWrapper(arr2, 2);
printf("%d\n", addArrays(obj1, obj2)); // Output: 10
char* str = arrayToString(obj1);
printf("%s\n", str); // Output: [1,2]
free(str);
return 0;
}using System;
using System.Linq;
public class ArrayWrapper {
private int[] nums;
public ArrayWrapper(int[] nums) {
this.nums = nums;
}
public static int operator +(ArrayWrapper a, ArrayWrapper b) {
return a.nums.Sum() + b.nums.Sum();
}
public override string ToString() {
return $"[{string.Join(",", nums)}]";
}
}
// Usage Example
var obj1 = new ArrayWrapper(new int[] {1,2});
var obj2 = new ArrayWrapper(new int[] {3,4});
Console.WriteLine(obj1 + obj2); // Output: 10
Console.WriteLine(obj1.ToString()); // Output: [1,2]This Python solution defines an ArrayWrapper class. It uses the magic methods __add__ for adding two instances together and __str__ for converting an instance to its string representation. __add__ method returns the sum of the numbers in both arrays, while __str__ method returns the string representation.
Time Complexity: O(n + m), where n and m are the lengths of the two arrays in the instances being added.
Space Complexity: O(1), as we do not use any additional space.
Approach 2: Interface Implementation for Addition and String Conversion
This approach focuses on languages that support the implementation of interfaces to achieve the desired functionality. We utilize relevant interfaces or methods required to override the behavior of arithmetic operations and object-to-string conversion.
class ArrayWrapper:
def __init__(self, nums):
self.nums = nums
def add(self, other):
return sum(self.nums) + sum(other.nums)
def to_string(self):
return str(self.nums)
# Usage Example
obj1 = ArrayWrapper([1,2])
obj2 = ArrayWrapper([3,4])
print(obj1.add(obj2)) # Output: 10
print(obj1.to_string()) # Output: [1, 2]class ArrayWrapper {
private int[] nums;
public ArrayWrapper(int[] nums) {
this.nums = nums;
}
public int add(ArrayWrapper other) {
return Arrays.stream(this.nums).sum() + Arrays.stream(other.nums).sum();
}
public String toString() {
return Arrays.toString(nums);
}
}
// Usage Example
ArrayWrapper obj1 = new ArrayWrapper(new int[]{1,2});
ArrayWrapper obj2 = new ArrayWrapper(new int[]{3,4});
System.out.println(obj1.add(obj2)); // Output: 10
System.out.println(obj1.toString()); // Output: [1, 2]This Python approach assumes an interface-like setup using methods, providing add and to_string methods to implement addition and string conversion respectively.
Time Complexity: O(n + m), for summing elements of both arrays.
Space Complexity: O(1), no additional space required.
Approach 3: Default Approach
class ArrayWrapper {
private nums: number[];
private s: number;
constructor(nums: number[]) {
this.nums = nums;
this.s = nums.reduce((a, b) => a + b, 0);
}
valueOf() {
return this.s;
}
toString() {
return `[${this.nums}]`;
}
}
/**
* const obj1 = new ArrayWrapper([1,2]);
* const obj2 = new ArrayWrapper([3,4]);
* obj1 + obj2; // 10
* String(obj1); // "[1,2]"
* String(obj2); // "[3,4]"
*/Complexity comparison
| Approach | Complexity |
|---|---|
| Operator Overloading to Implement Addition and String Conversion | Time Complexity: O(n + m), where n and m are the lengths of the two arrays in the instances being added. |
| Interface Implementation for Addition and String Conversion | Time Complexity: O(n + m), for summing elements of both arrays. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Operator Overloading with valueOf / toString | O(n) | O(1) | Best for JavaScript-style implementations where operator behavior can be customized directly. |
| Interface or Magic Method Implementation | O(n) | O(1) | Useful in Python, Java, or similar languages that define arithmetic and string behavior through special methods. |
Frequently asked questions
Is Array Wrapper easy or hard?
Array Wrapper is categorized as an Easy problem. The challenge lies in understanding how programming languages allow objects to override numeric and string operations rather than designing complex algorithms.
Array Wrapper Python/Java solution
In Python, implement __add__ to control addition and __str__ for printing the array format. In Java, similar behavior can be implemented through custom methods or interfaces that compute sums and return formatted strings. Both approaches iterate through the array, resulting in O(n) time complexity.
How to solve Array Wrapper in O(n)?
Store the array inside a wrapper class and override numeric conversion behavior. When two objects are added, iterate through the stored elements to compute their sums and return the combined value. Implement a string conversion method that joins array elements into the format [a,b,c].
What is the best approach for Array Wrapper?
The operator overloading approach is the most common solution. Implement methods such as valueOf (JavaScript) or __add__ (Python) to define how wrapper objects behave when added, and toString or __str__ for formatting. This keeps the implementation concise and matches the problem's design goal of customizing operator behavior.
Is Array Wrapper asked at Google/Amazon/Meta?
Array Wrapper is mainly a concept-check problem focused on operator overloading and object behavior. While not commonly reported as a direct Google or Meta interview question, the underlying concepts appear in object-oriented design and language feature questions.
What data structure is used in Array Wrapper?
The primary data structure is a simple integer array stored inside a wrapper class. The problem focuses less on advanced data structures and more on object-oriented techniques such as method overriding and operator customization.
What is the time complexity of Array Wrapper?
The time complexity is O(n) because computing the sum of the wrapped array requires iterating through its elements. String conversion also takes O(n) since each element must be included in the formatted output. Space complexity is O(1) beyond storing the original array.
