Program to check how many queries finds valid arithmetic sequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and also have list of queries. Where each query element contains [i, j]. So this query is asking whether the sublist of nums from [i, j] (both inclusive), is an arithmetic sequence or not. So finally we have to find the count of queries that return true.

So, if the input is like nums = [2, 4, 6, 8, 7, 6, 5, 2] queries = [[3, 4],[0, 3],[2, 4]], then the output will be 2, because [2, 4, 6, 8] is an arithmetic sequence, so query [0, 3] is true. and for [8, 7] is also an arithmetic sequence, so query [3, 4] is also true. but [6, 8, 7] is not an arithmetic sequence, so [2, 4] is not true.

To solve this, we will follow these steps −

  • if nums is empty, then
    • return 0
  • n := size of nums
  • diff := a list with elements (nums[i + 1] - nums[i]) for each i in range 0 to n - 2
  • rle := a list of size (n - 1) and fill with 0
  • for i in range 0 to n - 2, do
    • if i > 0 and diff[i] is same as diff[i - 1], then
      • rle[i] := rle[i - 1] + 1
    • otherwise,
      • rle[i] := 1
  • ans := 0
  • for each (i, j) in queries, do
    • if i is same as j, then
      • ans := ans + 1
    • otherwise,
      • ans := ans + (1 if rle[j - 1] >= (j - i), otherwise 0)
  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(nums, queries):
   if not nums:
      return 0

   n = len(nums)
   diff = [nums[i + 1] - nums[i] for i in range(n - 1)]

   rle = [0] * (n - 1)
   for i in range(n - 1):
      if i > 0 and diff[i] == diff[i - 1]:
         rle[i] = rle[i - 1] + 1
      else:
         rle[i] = 1

   ans = 0
   for i, j in queries:
      if i == j:
         ans += 1
      else:
         ans += rle[j - 1] >= (j - i)
   return ans

nums = [2, 4, 6, 8, 7, 6, 5, 2]
queries = [[3, 4],[0, 3],[2, 4]]
print(solve(nums, queries))

Input

[2, 4, 6, 8, 7, 6, 5, 2], [[3, 4],[0, 3],[2, 4]]

Output

2
raja
Updated on 16-Oct-2021 09:55:51

Advertisements