Prepin
Log in

Verify whether an array consists of consecutive integers.

Approach / Explanation

The candidate must create a program that determines whether the given array contains consecutive integers. Consecutive integers are those that appear in a sequence without any interruptions. For instance, [3, 4, 5, 6, 7] represents consecutive integers, while [3, 5, 6, 7] does not, as 4 is absent from the series. The integers in the sequence do not need to start from a specific number or increase by 1; they can be arranged in either ascending or descending order. For example, [5, 4, 3, 2, 1] also qualifies as consecutive integers. It is important to note that the question does not specify anything regarding negative integers, so a sequence like [0, -1, -2, -3] is also a valid possibility.

Suggested Answer

A simple method to tackle this problem is to begin by sorting the array, followed by verifying whether each element differs by 1 from the one before it. In Python, this can be implemented as shown below: def is_consecutive ( lst ) : lst = sorted ( lst ) for i in range ( 1 , len ( lst ) ) : if lst [ i ] - lst [ i - 1 ] != 1 : return False return True In this illustration, the array is sorted initially, and then each pair of adjacent elements is examined to see if they differ by 1. If any pair is identified with a difference not equal to 1, this indicates that the array does not consist of consecutive integers, and the function promptly returns False. Conversely, if no such pairs are found after evaluating all pairs, the function returns True, indicating that the array indeed contains consecutive integers.

Alternative Answer

A different and effective method involves identifying the minimum and maximum elements within the array. The elements of the array are consecutive if the total count of elements equals the difference between the maximum and minimum elements, plus one, and if all elements are distinct. Below is a Python implementation: def is_consecutive ( lst ) : min_element = min ( lst ) max_element = max ( lst ) if len ( lst ) != max_element - min_element + 1 : return False return len ( lst ) == len ( set ( lst ) ) In this code, min(lst) and max(lst) return the smallest and largest elements, respectively. The function len(lst) provides the total number of elements in the list, while len(set(lst)) counts the number of unique items. This uses the built-in set() function, which eliminates duplicates. If there are any repeated values in the array, the set will have fewer elements than the list, leading the function to return False .

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.