Similar Problems

Similar Problems not available

Find The Array Concatenation Value - Leetcode Solution

Companies:

LeetCode:  Find The Array Concatenation Value Leetcode Solution

Difficulty: Easy

Topics: two-pointers array simulation  

Problem Description:

Given an array of positive integers arr, you should consider all of its contiguous subarrays of length greater than or equal to 2. For each subarray, you should take the concatenation of all the elements in it, and add that value to your final answer.

Return the final answer modulo 10^9 + 7.

Example:

Input: arr = [1,2,3,4] Output: 20 Explanation: Concatenating all contiguous subarrays gives: [1,2] = 12 [1,2,3] = 123 [1,2,3,4] = 1234 [2,3] = 23 [2,3,4] = 234 [3,4] = 34 sum = 12 + 123 + 1234 + 23 + 234 + 34 = 20

Solution:

Algorithm:

  1. Initialize a variable 'result' to 0 and 'mod' to 10^9 + 7
  2. Traverse the array from left to right and for each element 'a' from l to r
  3. Calculate the partial sum of the subarray 'arr[l:r+1]' by multiplying 'a' with 10^(r-i) and adding it to the 'partial_sum'
  4. Update the 'result' with 'partial_sum' for each subarray
  5. Return the 'result' modulo 'mod'

Code:

def concatenation_sum(arr): result = partial_sum = 0 mod = 10**9 + 7

for i, a in enumerate(arr):
    partial_sum = (partial_sum * 10 + a) % mod
    result = (result + partial_sum) % mod
    if i != len(arr) - 1:
        partial_sum = (partial_sum * 10 + a) % mod

return result % mod

Time Complexity: O(n) Space Complexity: O(1)

Explanation:

In this problem, we need to consider subarrays of length greater than or equal to 2 and calculate the concatenation of all of its elements. To calculate concatenation of all elements in the subarray, we can first calculate the partial sum of the subarray and multiply it with the power of 10 to the number of digits in the remaining subarray elements.

We can traverse the array from left to right and for each element 'a' from l to r, we can calculate the partial sum of the subarray from arr[l:r+1] by multiplying 'a' with 10^(r-i) and adding it to the 'partial_sum'. We can then update the 'result' with 'partial_sum' for each subarray.

We also need to consider all contiguous subarrays of length greater than or equal to 2. Hence, if we are not at the last element, we need to update the 'partial_sum' by multiplying it with 10 and adding the current element 'a' to it.

Finally, we can return the 'result' modulo '10^9 + 7'.

Find The Array Concatenation Value Solution Code

1