Window with the most copies of a target value
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft and Tesla. It tests arrays and sliding window.
Implement most_target_window(nums, target_index, window_size).
The target value is nums[target_index]. Look at every contiguous subarray of nums with exactly window_size elements. Return the starting index of the one that contains the target value the most times. If several windows tie, return the smallest starting index.
The answer window does not need to include position target_index.
Input
-
nums: a list of integers,1 <= len(nums) <= 10^5. -
target_index: an index intonums. -
window_size: the window length,1 <= window_size <= len(nums).
Return -1 if the input is invalid (empty array, target_index out of range, or window_size outside [1, len(nums)]).
Aim for O(n) time and O(1) extra space.
Example 1
nums = [4, 7, 1, 4, 4, 4, 2], target_index = 0, window_size = 3
target = 4
copies of 4 per window start: 0->1, 1->1, 2->2, 3->3, 4->2
answer: 3 (window [4, 4, 4])
Example 2
nums = [1, 2, 1, 2], target_index = 0, window_size = 2
target = 1
every window holds one 1
answer: 0 (tie, smallest start)
Clarifying questions
- Is a negative
target_indexinvalid, or does it count from the end as in Python? - If
window_size == len(nums), is the answer always0? - Is the return value the start index only, not the count?
- Should invalid input return
-1or raise?
What a strong answer covers
- Validates the input first and reads the target value.
- Counts the target in the first window, then slides one step at a time, adding the entering element and subtracting the leaving one.
- Updates the best start only on a strictly larger count, which keeps the smallest start on ties.
-
O(n)time andO(1)extra space. - Tests both examples,
window_size = len(nums),window_size = 1, and each invalid input.
Follow-ups
- Return every start that ties for the best.
- Answer many
(target, window_size)queries on the same array. - The window may have any length up to
window_size; maximise the density of the target instead.
Where it's asked
What it tests
arrays · sliding window
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.

