Skip to main content

Subarray with Maximum Target Frequency

easy
Software engineer

You are given an integer array nums, an integer targetIndex, and an integer windowSize. The "target value" is defined as the value located at nums[targetIndex].

Find the starting index of a contiguous subarray of length windowSize that contains the maximum number of occurrences of the target value. If there are multiple such subarrays with the same maximum count, return the one with the minimum starting index.

Example 1

Input

nums = [1, 2, 3, 2, 2, 1, 2], targetIndex = 1, windowSize = 3

Output

1

Explanation

The target value is nums[1], which is 2. We look at all contiguous subarrays of length 3:
- Index 0: [1, 2, 3] contains one '2'.
- Index 1: [2, 3, 2] contains two '2's.
- Index 2: [3, 2, 2] contains two '2's.
- Index 3: [2, 2, 1] contains two '2's.
- Index 4: [2, 1, 2] contains two '2's.
The maximum frequency is 2. The starting indices with this frequency are 1, 2, 3, and 4. The minimum starting index is 1.

Example 2

Input

nums = [5, 5, 5, 1], targetIndex = 0, windowSize = 2

Output

0

Example 3

Input

nums = [1, 2, 1, 2, 1, 2], targetIndex = 0, windowSize = 2

Output

0

Constraints

  • 1 <= nums.length <= 10⁵
  • 0 <= targetIndex < nums.length
  • 1 <= windowSize <= nums.length
  • -10⁹ <= nums[i] <= 10⁹

Onsite

ArrayCountingSliding WindowTwo Pointers
Language
Code editor loads in the browser.

Output

Input

[1,2,3,2,2,1,2]
1
3

Expected

1

Your output

Run to see your output.