Syntax error Program to check whether given list is in valid state or not in Python

Program to check whether given list is in valid state or not in Python



Suppose we have a list of numbers called nums, we have to check whether every number can be grouped using one of the following rules: 1. Contiguous pairs (a, a) 2. Contiguous triplets (a, a, a) 3. Contiguous triplets (a, a + 1, a + 2)

So, if the input is like nums = [7, 7, 3, 4, 5], then the output will be True, as We can group [7, 7] together and [3, 4, 5] together.

To solve this, we will follow these steps −

  • n := size of nums

  • dp := a list of size n+1, first value is True, others are False

  • for i in range 2 to n, do

    • if i >= 2 and dp[i − 2] is not 0, then

      • if nums[i − 1] is same as nums[i − 2], then

        • dp[i] := True

    • if i >= 3 and dp[i − 3] is not 0, then

      • if (nums[i − 1], nums[i − 2], nums[i − 3]) are same or (nums[i − 1], nums[i − 2] + 1, nums[i − 3] + 2 are same), then

        • dp[i] := True

  • return dp[n]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      n = len(nums)
      dp = [True] + [False] * n
      for i in range(2, n + 1):
         if i >= 2 and dp[i − 2]:
            if nums[i − 1] == nums[i − 2]:
               dp[i] = True
         if i >= 3 and dp[i − 3]:
            if (nums[i − 1] == nums[i − 2] == nums[i − 3]) or (nums[i − 1] == nums[i − 2] + 1 == nums[i − 3] + 2):
               dp[i] = True
         return dp[n]
ob = Solution()
nums = [8, 8, 4, 5, 6]
print(ob.solve(nums))

Input

[8, 8, 4, 5, 6]

Output

True
Updated on: 2020-10-21T12:31:10+05:30

398 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements