KatInterview

Reverse Array Segment Between First Two Target Occurrences

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingarraystwo-pointersslicing

Last 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.