KatInterview

Track Target Occurrence Patterns Across Array Regions

Arrays & HashingAuto-graded · 19 test cases
EasyAuto-gradedArrays & Hashingarray-traversalboolean-flagsearly-termination

Last updated

Identifies whether a target value occurs at even/odd indices and in the first/second half of an even-length array in one pass.

Problem Statement

Given an array nums of integers with even length and a target integer target, determine whether target appears in four distinct categories within the array:

  1. Even-indexed position: Does target occur at any index where i % 2 == 0?
  2. Odd-indexed position: Does target occur at any index where i % 2 == 1?
  3. First half: Does target occur in the first half of the array (indices 0 through n//2 - 1)?
  4. Second half: Does target occur in the second half of the array (indices n//2 through n - 1)?

A single occurrence of target can satisfy multiple categories simultaneously. For instance, if target appears at index 0, it satisfies both the even-indexed and first-half categories.

Return a list of four boolean values [even_index, odd_index, first_half, second_half] indicating whether each category contains at least one occurrence of target.

Implement an efficient solution that scans the array once from left to right and stops early if all four categories are satisfied before reaching the end.

Constraints

  • 2 <= len(nums) <= 10^5
  • len(nums) is always even
  • -10^9 <= nums[i], target <= 10^9

Examples

Example 1

Input: track_target_regions([4, 2, 4, 7, 1, 4], 4)

Output: [True, True, True, True]

Example 2

Input: track_target_regions([1, 3, 5, 7], 3)

Output: [False, True, True, False]

Hints

Hint 1

Each occurrence of target updates exactly one parity flag (even or odd index) and one half flag (first or second half).

Hint 2

Use four boolean flags and update them during a single pass through the array.

Hint 3

Once all four flags become True, you can terminate early since no future element will change the result.