- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 Python
Suppose we have an array of numbers called nums. We have to check whether it contains contiguous values or not.
So, if the input is like nums = [6, 8, 3, 5, 4, 7], then the output will be true as the elements are 3, 4, 5, 6, 7, 8.
To solve this, we will follow these steps −
- if size of nums < 1, then
- return False
- min_val := minimum of nums, max_val := maximum of nums
- if (max_val - min_val + 1) is same as size of nums , then
- for i in range 0 to size of nums, do
- if nums[i] < 0, then
- j:= -nums[i] - min_val
- otherwise,
- j := nums[i] - min_val
- if nums[j] > 0, then
- nums[j] := -nums[j]
- otherwise,
- return False
- if nums[i] < 0, then
- return True
- for i in range 0 to size of nums, do
- return False
Let us see the following implementation to get better understanding −
Example
def solve(nums): if len(nums) < 1: return False min_val = min(nums) max_val = max(nums) if max_val - min_val + 1 == len(nums): for i in range(len(nums)): if nums[i] < 0: j = -nums[i] - min_val else: j = nums[i] - min_val if nums[j] > 0: nums[j] = -nums[j] else: return False return True return False nums = [6, 8, 3, 5, 4, 7] print(solve(nums))
Input
[6, 8, 3, 5, 4, 7]
Output
True
Advertisements