Task 1: Target Index
You are given an array of integers, @ints, and a target element $k.
Write a script to return the list of indices in the sorted array where the element is the same as the given target element.
Example 1: Input: @ints = (1, 5, 3, 2, 4, 2), $k = 2 → Output: (1, 2)
Example 2: Input: @ints = (1, 2, 4, 3, 5), $k = 6 → Output: ()
Example 3: Input: @ints = (5, 3, 2, 4, 2, 1), $k = 4 → Output: (4)
Method Explanation
To find the 0-based indices where the target integer $k appears in the sorted version of @ints:
- Sort the input array in ascending numerical order.
- Filter the indices
0 .. N-1to retain only those positions where the sorted value equals$k.
Sorting takes $O(N \log N)$ time and scanning for matching indices takes $O(N)$ time, giving an overall $O(N \log N)$ time complexity and $O(N)$ auxiliary space.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
signature_for find_target_indices => (
method => 0,
positional => [ ArrayRef [Int], Int ],
);
sub find_target_indices ( $ints, $k ) {
my @sorted = sort { $a <=> $b } @$ints;
my @target_indices = grep { $sorted[$_] == $k } 0 .. $#sorted;
return \@target_indices;
}
Python Solution
def find_target_indices(ints: list[int], k: int) -> list[int]:
"""Return the indices in the sorted array where the element equals k."""
sorted_ints = sorted(ints)
return [i for i, val in enumerate(sorted_ints) if val == k]