|
U
Pro24. Count Target Occurrences and Indices
Easy
Problem Description
Given an array of N integers and a target value T, count how many times T appears, and print all 0-based indices where it occurs in ascending order.
Input Format
- •Line 1: Two space-separated integers N and T (1≤N≤105, −109≤T≤109).
- •Line 2: N space-separated integers A0,A1,…,AN−1.
Output Format
- •Line 1: An integer representing count of occurrences.
- •Line 2: Space-separated 0-based indices where T occurs, or
-1if 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
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit