Program to convert one list identical to other with sublist sum operation in Python


Suppose we have two lists l1 and l2, we have to make the lists equal by applying this operation repeatedly − Choose a sublist, and replace the whole sublist with its sum. Finally return the size of the longest resulting list possible after applying above operations. If there's no solution, return -1.

So, if the input is like l1 = [1, 4, 7, 1, 2, 10] l2 = [5, 6, 1, 3, 10], then the output will be 4, as if we perform this operation as follows −

  • Take l1's sublist [1, 4] we get [5, 7, 1, 2, 10]
  • Take l1's sublist [1, 2] we get [5, 7, 3, 10]
  • Take l2's sublist [6, 1] we get [5, 7, 3, 10].

To solve this, we will follow these steps −

  • i := size of l1 - 1, j := size of l2 - 1, res := 0
  • while i >= 0 and j >= 0, do
    • if l1[i] is same as l2[j], then
      • res := res + 1, i := i - 1, j := j - 1
    • otherwise when l1[i] < l2[j], then
      • if i > 0 is non-zero, then
        • l1[i - 1] := l1[i - 1] + l1[i]
      • i := i - 1
    • otherwise when l1[i] > l2[j], then
      • if j > 0, then
        • l2[j - 1] := l2[j - 1] + l2[j]
      • j := j - 1
  • return res if i is same as -1 and j is same as -1 otherwise return -1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, l1, l2):
      i, j, res = len(l1) - 1, len(l2) - 1, 0
      while i >= 0 and j >= 0:
         if l1[i] == l2[j]:
            res, i, j = res + 1, i - 1, j - 1
         elif l1[i] < l2[j]:
            if i > 0:
               l1[i - 1] += l1[i]
            i -= 1
         elif l1[i] > l2[j]:
            if j > 0:
               l2[j - 1] += l2[j]
            j -= 1
         return res if i == -1 and j == -1 else -1
ob = Solution()
l1 = [1, 4, 7, 1, 2, 10]
l2 = [5, 6, 1, 3, 10] print(ob.solve(l1, l2))

Input

[1, 4, 7, 1, 2, 10], [5, 6, 1, 3, 10]

Output

4

Updated on: 19-Oct-2020

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements