
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Array Elements Are Consecutive in O(N) Time and O(1) Space 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
Advertisements