Prepin
Log in

Locate the position of 0 to substitute in order to achieve the longest sequence of consecutive ones.

Approach / Explanation

This question involves an array containing binary values, specifically 0s and 1s. You need to identify the index of a 0 that, when changed to 1, will create the longest consecutive sequence of 1s. As you analyze the problem, keep in mind that you are searching for the index of a 0 that maximizes the lengths of the 1s sequences both before and after it. Here are some steps to consider when tackling this problem: Iterate through the array while tracking the current index of 0 and the indices of the last two sequences of 1s. Each time you encounter a new 0, compute the length of the continuous 1s sequence that would form if that 0 were converted to 1. If this length exceeds the current maximum, update the index of the 0 to be replaced.

Suggested Answer

For example, with the input array [1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1], the correct output would be index 2. In this case, if you change the 0 at index 2 to a 1, you create the longest stretch of continuous ones: [1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1]. Conversely, changing any other 0 results in a shorter sequence of ones.

Alternative Answer

Consider the array [1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]. Here, the optimal index for replacement is 5. By changing the 0 at index 5, the resulting sequence is [1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0], which creates the longest series of consecutive ones. Replacing any other 0 yields a shorter sequence. In both scenarios, the key factor in selecting which 0 to replace was the number of 1s on either side of each 0. It's important to carefully identify and monitor the correct sequences as you work through the array.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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