Check if an array contains all elements of a given range in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums. We also have two numbers x and y defining a range [x, y]. We have to check whether the array contains all elements in the given range or not.

So, if the input is like nums = [5,8,9,6,3,2,4] x = 2 y = 6, then the output will be true as there are all elements [2,3,4,5,6].

To solve this, we will follow these steps −

  • temp_range := y - x
  • for i in range 0 to size of nums, do
    • if |nums[i]| >= x and |nums[i]| <= y, then
      • z := |nums[i]| - x
      • if nums[z] > 0, then
        • nums[z] := -nums[z]
  • cnt := 0
  • for i in range 0 to temp_range, do
    • if i >= size of nums, then
      • come out from loop
    • if nums[i] > 0, then
      • return False
    • otherwise,
      • cnt := cnt + 1
  • if cnt is not same as (temp_range + 1), then
    • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums, x, y) :
   temp_range = y - x
   for i in range(0, len(nums)):
      if abs(nums[i]) >= x and abs(nums[i]) <= y:
         z = abs(nums[i]) - x
         if (nums[z] > 0) :
            nums[z] = nums[z] * -1
   cnt = 0
   for i in range(0, temp_range + 1):
      if i >= len(nums):
         break
      if nums[i] > 0:
         return False
      else:
         cnt += 1
   if cnt != temp_range + 1:
      return False
   return True
nums = [5,8,9,6,3,2,4]
x = 2
y = 6
print(solve(nums, x, y))

Input

[5,8,9,6,3,2,4], 2, 6

Output

True
raja
Published on 30-Dec-2020 17:11:31
Advertisements