Difficulty: Easy | Acceptance: 89.10% | Paid: No Topics: N/A
Create a class ArrayWrapper that wraps an array of integers and provides the following methods:
-
ArrayWrapper(int[] nums): Initializes the object with the array nums.
-
String toString(): Returns a string representation of the wrapped array in the format “[1,2,3]“.
-
int add(ArrayWrapper other): Returns the sum of all elements in the current array and the other array.
-
Examples
-
Constraints
Examples
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 <= 1000
0 <= nums[i] <= 1000
Direct Implementation
Intuition Store the array in the class and implement each method by directly iterating through the elements.
Steps
- Store the array in the constructor
- For toString, iterate through elements and build the string representation
- For add, iterate through both arrays and sum all elements
class ArrayWrapper:
def __init__(self, nums):
self.nums = nums
def add(self, other):
total = 0
for num in self.nums:
total += num
for num in other.nums:
total += num
return total
def __str__(self):
result = "["
for i, num in enumerate(self.nums):
if i > 0:
result += ","
result += str(num)
result += "]"
return resultComplexity
- Time: O(n + m) for add, O(n) for toString where n and m are the lengths of the arrays
- Space: O(n) for toString (to store the result string), O(1) for add
- Notes: Simple and straightforward implementation
Using Built-in Methods
Intuition Leverage language-specific built-in methods for array operations to simplify the code.
Steps
- Store the array in the constructor
- Use built-in join/toString methods for string representation
- Use built-in sum/reduce methods for addition
class ArrayWrapper:
def __init__(self, nums):
self.nums = nums
def add(self, other):
return sum(self.nums) + sum(other.nums)
def __str__(self):
return "[" + ",".join(str(num) for num in self.nums) + "]"Complexity
- Time: O(n + m) for add, O(n) for toString where n and m are the lengths of the arrays
- Space: O(n) for toString (to store the result string), O(1) for add
- Notes: More concise code using built-in functions