LeetCode 2695: Array Wrapper Solution

Master LeetCode problem 2695 (Array Wrapper), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2695. Array Wrapper

Easy

Problem Explanation

Explanation

To solve this problem, we will create a class ArrayWrapper with two overloaded operators: + for adding two instances of the class and String() for converting the array to a string format. We will implement the addition by summing up the elements of the arrays and the String() function by returning a comma-separated string surrounded by brackets.

Solution Code

class ArrayWrapper {
    private int[] nums;

    public ArrayWrapper(int[] nums) {
        this.nums = nums;
    }

    public int sum() {
        int total = 0;
        for (int num : nums) {
            total += num;
        }
        return total;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < nums.length; i++) {
            sb.append(nums[i]);
            if (i < nums.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    public static ArrayWrapper add(ArrayWrapper a, ArrayWrapper b) {
        int[] result = new int[a.nums.length + b.nums.length];
        System.arraycopy(a.nums, 0, result, 0, a.nums.length);
        System.arraycopy(b.nums, 0, result, a.nums.length, b.nums.length);
        return new ArrayWrapper(result);
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2695 (Array Wrapper)?

This page provides optimized solutions for LeetCode problem 2695 (Array Wrapper) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2695 (Array Wrapper)?

The time complexity for LeetCode 2695 (Array Wrapper) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2695 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2695 in Java, C++, or Python.

Back to LeetCode Solutions