Report Where a Value Appears
UpstartSoftware Engineer · Online AssessmentLast updated
Check whether a target value appears at an even index, an odd index, the first half, and the second half of an even-length list in a single scan.
Problem Statement
You are given an array of integers nums with an even length n, and an integer target.
You need to determine the presence of target in four specific regions/categories of the array:
- Even Index: Does
targetappear at any even index (i % 2 == 0)? - Odd Index: Does
targetappear at any odd index (i % 2 == 1)? - First Half: Does
targetappear in the first half of the array (i = n // 2)?
A single occurrence of target at index i can simultaneously satisfy multiple conditions (e.g., index 0 satisfies both Even Index and First Half).
Return a list of four booleans [has_even, has_odd, has_first_half, has_second_half] corresponding to the four conditions.
To optimize runtime, scan the array from left to right and terminate early if all four conditions become True.
Function Signature
def report_target_positions(nums: list[int], target: int) -> list[bool]:
pass
Examples
Example 1
Input: nums = [4, 2, 4, 7, 1, 4], target = 4
Output: [True, True, True, True]
Explanation:
n = 6, so the first half is indices0, 1, 2and the second half is indices3, 4, 5.target = 4appears at indices0(even, first half),2(even, first half), and5(odd, second half).- Since all 4 categories are covered, the result is
[True, True, True, True].
Example 2
Input: nums = [1, 3, 5, 7], target = 3
Output: [False, True, True, False]
Explanation:
target = 3appears only at index1.- Index
1is odd and belongs to the first half (1 < 2). - It does not appear at any even index or in the second half.
Constraints
2 <= len(nums) <= 10^5len(nums) % 2 == 0-10^9 <= nums[i], target <= 10^9
Hints
Hint 1
Precompute the midpoint `mid = len(nums) // 2` before iterating to quickly evaluate the half-array condition.
Hint 2
When `nums[i] == target`, update the respective boolean flags based on `i % 2` and whether `i < mid`.
Hint 3
Check if all four flags are `True` after updating, and `break` the loop immediately if so.
Follow-up questions
- How would you adapt the logic if the array length can be odd, where the middle element belongs to neither half?
- If you needed to check multiple targets on the same static array, how would you preprocess the data for O(1) query time?
- How would you implement this using bit manipulation to track all four flags in a single integer mask?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.