Similar Problems

Similar Problems not available

Array With Elements Not Equal To Average Of Neighbors - Leetcode Solution

Companies:

LeetCode:  Array With Elements Not Equal To Average Of Neighbors Leetcode Solution

Difficulty: Medium

Topics: greedy sorting array  

Problem Statement

Given an array nums of distinct integers, return an array answer of length n such that answer[i] is equal to the sum of the elements of nums not counting nums[i].

In other words, answer[i] is the sum of all nums[j] (j != i).

Constraints:

  • n == nums.length
  • 1 <= n <= 100
  • -1000 <= nums[i] <= 1000
  • All the elements of nums are unique.

Example:

Input: nums = [1,2,3,4,5] Output: [14,13,12,11,10] Explanation: For each element i of the output array, answer[i] = sum([1,2,3,4,5]) - nums[i].

Solution:

To solve this problem, we need to loop over the input array and calculate the sum of all elements of the array except the current element. This can be done easily by calculating the sum of all elements of the input array first and then subtracting the current element from the sum.

The time complexity of the solution is O(n) as we are looping over the array only once.

Here's the code for the solution:

class Solution { public: vector<int> getSumAbsoluteDifferences(vector<int>& nums) { int n = nums.size(); int sum = accumulate(nums.begin(), nums.end(), 0); vector<int> ans(n);

    for(int i = 0; i < n; i++) {
        ans[i] = (sum - nums[i]) - (n - 1 - i) * nums[i] + i * nums[i] - (i == 0 ? 0 : ans[i - 1]); 
    }
    return ans;
}

};

Let's go through the code step by step:

  1. We start by getting the size of the input array and the sum of all elements of the array using the accumulate function in the STL.

  2. We initialize a vector ans of size n to store the result.

  3. We loop over the input array and calculate the sum of all elements of the array except the current element. Here, we use the formula (sum - nums[i]) to get the sum of all elements except nums[i].

  4. We then subtract the sum obtained in the previous step from the sum of all elements of the array to get the sum of nums[i] multiplied by (n - 1).

  5. We then add the product of i and nums[i] to the sum calculated in step 4.

  6. We subtract the sum of the previous elements in the output array from the current sum to get the final result.

  7. Finally, we return the output array.

This solution has a runtime complexity of O(n).

Array With Elements Not Equal To Average Of Neighbors Solution Code

1