Code Logo

Duplicate Indices Map

Published at05 Jan 2026
Easy 37 views
Like27

You are given an array of numbers and need to describe where the repeated values appear, not just whether repeats exist.

That means this problem goes one step beyond a normal duplicate check. Instead of returning true or false, you must collect the positions of every value that appears more than once. Each repeated value should produce one group of indices. If a value appears only a single time, it should not be included in the answer at all.

For example, if nums = [1,2,3,1,2,1], the output should be [[0,3,5],[1,4]]. The first group belongs to the value 1, because 1 appears at indices 0, 3, and 5. The second group belongs to the value 2, because 2 appears at indices 1 and 4. The value 3 is not included, since it appears only once.

If nums = [7,7,7], the answer is [[0,1,2]] because all three positions belong to the same repeated value. If nums = [4,5,6], the answer is [] because every number is unique, so there are no duplicate groups to report.

The important detail is that the answer is organized by value occurrence groups, not by pair matching. You are not listing every repeated pair like [0,3] and [3,5] for the value 1. Instead, you collect all indices for that repeated value into one list.

So the task is to scan the array, group indices by the number they belong to, and return only the groups whose value appeared at least twice.

Example Input & Output

Example 1
Input
nums = [1,2,3,1,2,1]
Output
[[0,3,5],[1,4]]
Explanation

Value 1 appears at indices 0, 3, 5; value 2 appears at indices 1, 4.

Example 2
Input
nums = [4,5,6]
Output
[]
Explanation

No duplicates exist.

Example 3
Input
nums = [7,7,7]
Output
[[0,1,2]]
Explanation

Value 7 repeats across all positions.

Algorithm Flow

Recommendation Algorithm Flow for Duplicate Indices Map
Recommendation Algorithm Flow for Duplicate Indices Map

Solution Approach

A hash map works well here. Walk through the array once, and for each number append its current index to a list stored under that number.

After that pass, the map tells you every position where each value appeared. Go through the stored lists and keep only the ones whose length is at least 2.

That gives exactly the index groups for repeated values. This approach runs in O(n) time and uses O(n) extra space.

Best Answers

java
import java.util.*;
class Solution {
    public List<List<Integer>> duplicate_indices_map(int[] nums) {
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.computeIfAbsent(nums[i], k -> new ArrayList<>()).add(i);
        }
        List<List<Integer>> result = new ArrayList<>();
        for (List<Integer> indices : map.values()) {
            if (indices.size() > 1) {
                result.add(indices);
            }
        }
        return result;
    }
}