Program to check subarrays can be rearranged from arithmetic sequence or not in Python

PythonServer Side ProgrammingProgramming

Suppose we have sequence of numbers nums, and another two arrays l and r of size m, these l and r are representing range queries like [l[i], r[i]]. We have to find a Boolean sequence ans, where ans[i] is true when the subarray nums[l[i]], nums[l[i] + 1], ... nums[r[i] - 1], nums[r[i]] can be arranged to generate an arithmetic sequence, otherwise false.

A sequence is said to be arithmetic, if it consists of at least two elements, and the difference between every two consecutive elements is the same. For example, some arithmetic sequences are: [2, 4, 6, 8, 10], [5, 5, 5, 5], [4, -2, -8, -14], but not [2, 2, 3, 6, 9].

So, if the input is like nums = [6,8,7,11,5,9], l = [0,0,2], r = [2,3,5], then the output will be [True, False, True] because −

  • for query [0, 2], the sequence is [6,8,7], can be rearranged as [6,7,8], this is valid

  • for query [0, 3], the sequence is [6,8,7,11], cannot be rearranged in arithmetic sequence

  • for query [2, 5], the sequence is [7,11,5,9], can be rearranged as [5,7,9,11], this is valid

To solve this, we will follow these steps −

  • new := a list of size same as l and fill with all true values

  • for i in range 0 to size of l - 1, do

    • data := sublist of nums from index l[i] to r[i]

    • sort the list data

    • d := a new list

    • for j in range 0 to size of data - 2, do

      • insert data[j+1] - data[j] at the end of d

    • d := a new list from a new set from d

    • if size of d is not same as 1, then

      • new[i] := False

  • return new

Example

Let us see the following implementation to get better understanding −

def solve(nums, l, r):
   new = [True]*len(l)

   for i in range(len(l)):
      data = nums[l[i]:r[i]+1]
      data.sort()

      d = []
      for j in range(len(data) - 1):
         d.append(data[j+1] - data[j])

      d = list(set(d))
      if len(d) != 1:
         new[i] = False
   return new

nums = [6,8,7,11,5,9]
l = [0,0,2]
r = [2,3,5]
print(solve(nums, l, r))

Input

[6,8,7,11,5,9], [0,0,2], [2,3,5]

Output

[True,False,True]
raja
Updated on 06-Oct-2021 07:09:18

Advertisements