
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python
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]
- if nums[i] < init_term, then
- 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
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
- Related Articles
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Find median of BST in O(n) time and O(1) space in Python
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- Find the maximum repeating number in O(n) time and O(1) extra space in Python
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python
- Find median of BST in O(n) time and O(1) space in C++
- Rearrange array in alternating positive & negative items with O(1) extra space in C++
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Find duplicate in an array in O(n) and by using O(1) extra space in C++
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Check if array elements are consecutive in Python
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++

Advertisements