Prepin
Log in

Identify the longest subarray composed of consecutive integers.

Approach / Explanation

The task involves identifying the largest subarray consisting entirely of consecutive integers. In the context of an array, a subarray refers to a contiguous section of the array, which can include the entire array itself. It's important to note that subsequences are different from subarrays, as they do not require the elements to be contiguous. The goal is to determine the longest subarray where every element is a consecutive integer. To tackle this problem, consider the following steps: Examine each subarray one at a time. Verify that the difference between the maximum and minimum values is exactly n-1 , and that the number of unique elements equals n . If both conditions are satisfied, the subarray contains consecutive integers. Implement this by setting up two variables ( min and max ) to track the endpoints of the current subarray and updating them whenever a larger consecutive subarray is identified. Utilize a set data structure to hold the elements, which will help in checking for duplicates within the subarray.

Suggested Answer

Let's examine an example with the array [2, 0, 1, 0, 2, 1, 0] . The longest subarrays consisting of consecutive elements are [2, 0, 1] , [0, 2, 1] , or [0, 1, 2] . The Python code to tackle this issue may be structured as follows: def find_max_subarray ( array ) : length = len ( array ) max_len_so_far = - 1 for i in range ( length ) : min_value = array [ i ] max_value = array [ i ] elements = { array [ i ] } for j in range ( i + 1 , length ) : if array [ j ] in elements : break elements . add ( array [ j ] ) min_value = min ( min_value , array [ j ] ) max_value = max ( max_value , array [ j ] ) if max_value - min_value == j - i : max_len_so_far = max ( max_len_so_far , max_value - min_value + 1 ) return max_len_so_far

Alternative Answer

Let's take another example with the array [10, 12, 11, 15] . In this case, the longest subarray containing consecutive elements is [10, 12, 11] , [12, 10, 11] , or [10, 11, 12] . You can use this array in the same code previously provided to address this problem: array = [ 10 , 12 , 11 , 15 ] print ( find_max_subarray ( array ) ) The result of running this code will also be 3 , representing the length of the longest subarray with consecutive elements.

Question Details

Difficulty & Category

Medium
algorithms

Companies

LinkedIn

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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