Maximum Consecutive Good Numbers

Asked atAmazon
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an array of integers nums and an array goodNumbers, return the **maximum **number of **consecutive **good numbers in the array.

Any number present in the **goodNumbers **array is a good number.

Input: nums = [1, 2, 3, 5, 4, 5, 1], goodNumbers = [3, 5] Output: 2 Explanation: [1, 2, 3, 5, 4, 5, 1] the underlined numbers are all good numbers and give the maximum length.

Input: nums = [4, 8, 1, 2, 0, 4, 6], goodNumbers = [1, 4, 2, 6] Output: 2 Explanation: [4, 8, 1, 2, 0, 4, 6] the underlined numbers are all good numbers and give the maximum length. Note that the segment with index** [5, 6]** (0 - Based) was also a possible answer.

  • 1 <= nums.length <= 105
  • 1 <= goodNumbers.length <= 105
  • -104 <= nums[i], goodNumbers[i] <= 104

cpp

class Solution {
public:
    int maxConsecutiveGoodNums(vector<int>& nums, vector<int>& goodNumbers) {

    }
};

java

class Solution {
    public int maxConsecutiveGoodNums(int[] nums, int[] goodNumbers) {
        
    }
}

python

class Solution:
    def maxConsecutiveGoodNums(self, nums, goodNumbers):

javascript

class Solution {
    maxConsecutiveGoodNums(nums, goodNumbers) {

    }
}

csharp

public class Solution {
    public int MaxConsecutiveGoodNums(List<int> nums, List<int> goodNumbers) {

    }
}

go

func maxConsecutiveGoodNums(nums []int, goodNumbers []int) int {

}
Stuck? Show a way to structure it+
  1. 01Put good numbers in a hash set.
  2. 02Scan nums once.
  3. 03Increment a current run for good values and reset otherwise.
  4. 04Track the largest current run.

Reference answer

Then expect these follow-ups

  • How would you return the run boundaries?

    Tests: index tracking

  • How would dynamic updates to goodNumbers change the design?

    Tests: data structures

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question