Reverse Array Segment Between First Two Target Occurrences
Arrays & HashingAuto-graded · 23 test casesLast updated
Reverse the subsegment of an array from the first occurrence of a target value up to its second occurrence.
Given an array of integers a and a target value k, identify the first two indices where k appears in the array.
If k appears at least twice, reverse the inclusive subsegment of a starting at the first occurrence of k and ending at the second occurrence of k. Any element before the first occurrence or after the second occurrence must remain in its original position. Any occurrences of k beyond the second occurrence should be ignored.
If k appears fewer than two times in a, return a copy of the original array unchanged.
Constraints
- $0 \le \text{len}(a) \le 10^5$
- $-10^9 \le a[i], k \le 10^9$
Examples
Example 1
Input: reverse_between_equal_values([1, 2, 3, 2, 4], 2)
Output: [1, 2, 3, 2, 4]
Example 2
Input: reverse_between_equal_values([5, 1, 5], 5)
Output: [5, 1, 5]
Example 3
Input: reverse_between_equal_values([1, 2, 3], 2)
Output: [1, 2, 3]
Hints
Hint 1
Find the indices of the first two elements equal to `k` by scanning the array from left to right.
Hint 2
If fewer than two matches are found, return a copy of the input list.
Hint 3
Slice the array into three sections: elements before the first match, the reversed segment between the two matches (inclusive), and elements after the second match.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To solve this problem:
- Locate Target Indices: Perform a single linear scan over the array to locate the 0-based indices of the first two occurrences of
k.- Store the first position in
first_idxand the second position insecond_idx. - Once
second_idxis found, terminate the search early so subsequent occurrences ofkare ignored.
- Store the first position in
- Check Match Count: If
second_idxwas not populated (meaningkappeared 0 or 1 time), return a shallow copy of arraya. - Construct the Result: Rebuild the array by concatenating three parts:
- The prefix
a[:first_idx]. - The reversed slice
a[first_idx:second_idx + 1][::-1]. - The suffix
a[second_idx + 1:].
- The prefix
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the length of array
a. Finding the indices takes at most $N$ operations, and slicing/reversing the segment takes linear time proportional to the array size. - Space Complexity: $\mathcal{O}(N)$ to construct and return the modified output array.
from typing import List
def reverse_between_equal_values(a: List[int], k: int) -> List[int]:
first_idx = -1
second_idx = -1
for i, val in enumerate(a):
if val == k:
if first_idx == -1:
first_idx = i
else:
second_idx = i
break
if second_idx == -1:
return a[:]
return a[:first_idx] + a[first_idx:second_idx + 1][::-1] + a[second_idx + 1:]