Prepin
Log in

Identify the largest sub-array consisting of consecutive integers.

Approach / Explanation

This question presents an array of integers, and your objective is to identify the largest sub-array consisting of consecutive integers. A sub-array is defined as any continuous segment of the array. In this context, 'consecutive integers' means a sequence where each integer differs from the next by exactly one. It's important to note that this does not require the elements to be in strict ascending or descending order; rather, they should collectively form a continuous integer sequence. To tackle this problem, you might consider iterating through the array and expanding the current sub-array. However, a straightforward approach could lead to a runtime complexity of O(n^2). To improve efficiency, you can utilize a Set Data Structure, which reduces lookup times.

Suggested Answer

Here’s an example solution for the problem using the array [2, 0, 2, 1, 4, 3, 1, 0]. Start by initializing the result to 0. Next, traverse the array from left to right. For each element, first determine if it is the beginning of a sequence (make sure that (element - 1) is not present). If it is, then look for the subsequent elements in the sequence. Continue checking for incrementing values and keep a count. Track the highest count encountered. The final result will be the maximum count found. In this instance, the result would be [0, 1, 2, 3, 4], which equals 5.

Alternative Answer

Now, let’s consider another example where the input is [10, 12, 12, 10, 10, 11, 10]. First, set the result to 0. Traverse the array from left to right. For each element, determine if it marks the beginning of a sequence. If it does, check for the subsequent elements in that sequence. Continue to look for elements that are incrementing and keep a count of them. Additionally, keep a record of the highest count encountered. The final result will be the maximum count, which in this instance is [10, 11, 12] = 3.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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