
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
- Related Questions & Answers
- Check if Queue Elements are pairwise consecutive in Python
- Check if all array elements are distinct in Python
- Check if three consecutive elements in an array is identical in JavaScript
- Check if some elements of array are equal JavaScript
- Check if items in an array are consecutive but WITHOUT SORTING in JavaScript
- Check if list contains consecutive numbers in Python
- Check if all elements of the array are palindrome or nots in Python
- Check if all elements of the array are palindrome or not in Python
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python
- Python – Check if elements index are equal for list elements
- Python - Check if all elements in a List are same
- Python - Check if all elements in a list are identical
- How to check if array contains three consecutive dates in java?
- Check if the elements of stack are pairwise sorted in Python
- Consecutive elements sum array in JavaScript
Advertisements