Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of unsorted numbers called nums. We have to check whether it contains contiguous values or not, it should support negative numbers also.

So, if the input is like nums = [-3, 5, 1, -2, -1, 0, 2, 4, 3], then the output will be true as the elements are 3, 4, 5, 6, 7, 8.

To solve this, we will follow these steps −

  • size := size of nums
  • init_term := inf
  • for i in range 0 to size, do
    • if nums[i] < init_term, then
      • init_term := nums[i]
  • ap_sum := quotient of ((size * (2 * init_term + (size - 1) * 1)) / 2)
  • total := sum of all elements of nums
  • return true when ap_sum is same as total otherwise false

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums):
   size = len(nums)
   init_term = 999999
   for i in range(size):
      if nums[i] < init_term:
         init_term = nums[i]
   ap_sum = (size * (2 * init_term + (size - 1) * 1)) // 2
   total = sum(nums)
   return ap_sum == total
nums = [-3, 5, 1, -2, -1, 0, 2, 4, 3] 
print(solve(nums))

Input

[-3, 5, 1, -2, -1, 0, 2, 4, 3]

Output

True
raja
Published on 30-Dec-2020 17:48:32
Advertisements