U

24. Count Target Occurrences and Indices

Easy

Problem Description

Given an array of NN integers and a target value TT, count how many times TT appears, and print all 0-based indices where it occurs in ascending order.

Input Format

  • •Line 1: Two space-separated integers NN and TT (1≤N≤1051 \le N \le 10^5, −109≤T≤109-10^9 \le T \le 10^9).
  • •Line 2: NN space-separated integers A0,A1,…,AN−1A_0, A_1, \dots, A_{N-1}.

Output Format

  • •Line 1: An integer representing count of occurrences.
  • •Line 2: Space-separated 0-based indices where TT occurs, or -1 if count is 0.
Example 1:
Input:
6 5
1 5 3 5 5 2
Output:
3
1 3 4
Explanation: Target 5 appears 3 times at indices 1, 3, and 4.
Example 2:
Input:
4 10
1 2 3 4
Output:
0
-1
Explanation: Target 10 does not appear in the array.
Example 3:
Input:
1 7
7
Output:
1
0
Explanation: Target 7 appears once at index 0.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online