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.
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)
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.

