List Calculator Algorithm


Given a list of integers nums, a string op representing either “+”, “-“, “/”, or “*”, and an integer val, perform the operation on every number in nums with val and return the result.

Note: “/” is integer division.

Constraints
1 ≤ n ≤ 100,000 where n is the length of nums
Example 1
Input
nums = [3, 1, 6]
op = “+”
val = 4
Output
[7, 5, 10]
Explanation
We add 4 to every number in nums and return it.

Example 2
Input
nums = [3, -4, 1]
op = “*”
val = 2
Output
[6, -8, 2]
Explanation
We multiply every number in nums by 2.

C++ List Calculator Algorithm

We can first allocate an array/list and push each result into the array. The time complexity is O(N) and the space complexity is O(N).

1
2
3
4
5
6
7
8
9
10
11
12
vector<int> listCalculator(vector<int>& nums, string op, int val) {
    vector<int> res;
    for (auto &n: nums) {
        switch (op[0]) {
            case '+': res.push_back(n + val); break;
            case '-': res.push_back(n - val); break;
            case '*': res.push_back(n * val); break;
            case '/': res.push_back(n / val); break;
        }
    }
    return res;
}
vector<int> listCalculator(vector<int>& nums, string op, int val) {
    vector<int> res;
    for (auto &n: nums) {
        switch (op[0]) {
            case '+': res.push_back(n + val); break;
            case '-': res.push_back(n - val); break;
            case '*': res.push_back(n * val); break;
            case '/': res.push_back(n / val); break;
        }
    }
    return res;
}

Alternatively, we can modify the elements in the list in place. The time is O(N) and the space is O(1) constant.

1
2
3
4
5
6
7
8
9
10
11
vector<int> listCalculator(vector<int>& nums, string op, int val) {
    for (int i = 0; i < nums.size(); ++ i) {
        switch (op[0]) {
            case '+': nums[i] += val; break;
            case '-': nums[i] -= val; break;
            case '*': nums[i] *= val; break;
            case '/': nums[i] /= val; break;
        }
    }
    return nums;
}
vector<int> listCalculator(vector<int>& nums, string op, int val) {
    for (int i = 0; i < nums.size(); ++ i) {
        switch (op[0]) {
            case '+': nums[i] += val; break;
            case '-': nums[i] -= val; break;
            case '*': nums[i] *= val; break;
            case '/': nums[i] /= val; break;
        }
    }
    return nums;
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
340 words
Last Post: Teaching Kids Programming - Algorithms to Remove Nodes from a Linked List
Next Post: Teaching Kids Programming - Binary Search Algorithm to Compute the Square Root

The Permanent URL is: List Calculator Algorithm

Leave a Reply