Group numbers by remainder

Group numbers by remainder

Medium Java Collections 27 views
Explanation Complexity

Problem Statement

Task: group numbers by (value % m) and return a map remainder -> list of numbers.

Input Format

An integer n (size of array)
Then n integers (array elements)
An integer m

Output Format

A map where:

• key → value % m (remainder)

• value → list of numbers having that remainder

Example

6
1 2 3 4 5 6
3
0 -> [3, 6]
1 -> [1, 4]
2 -> [2, 5]

Constraints

• n ≥ 0

• m > 0

• Maintain the original order of numbers inside each list

Concept Explanation

Each number is grouped based on its remainder when divided by m.
All numbers with the same remainder go into the same list.

Step-by-Step Explanation

1.Read integer n and the array elements.

2.Read integer m.

3.Create an empty Map.

4.Loop through each number in the array:

• Compute rem = number % m.

5.If rem is not already a key in the map:

• Create a new empty list and put it in the map.

6.Add the current number to the list for key rem.

7.Continue for all numbers.

8.Return or print the map.

Concept Explanation

Each number is grouped based on its remainder when divided by m.
All numbers with the same remainder go into the same list.

Step-by-Step Explanation

1.Read integer n and the array elements.

2.Read integer m.

3.Create an empty Map.

4.Loop through each number in the array:

• Compute rem = number % m.

5.If rem is not already a key in the map:

• Create a new empty list and put it in the map.

6.Add the current number to the list for key rem.

7.Continue for all numbers.

8.Return or print the map.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (array elements)
An integer m
Output Format
A map where:

• key → value % m (remainder)

• value → list of numbers having that remainder
Constraints
• n ≥ 0

• m > 0

• Maintain the original order of numbers inside each list

Examples

Input:
6 1 2 3 4 5 6 3
Output:
0 -> [3, 6] 1 -> [1, 4] 2 -> [2, 5]

Example Solution (Public)

Java
static java.util.Map<Integer,java.util.List<Integer>> groupByRemainder(int[] a,int m){java.util.HashMap<Integer,java.util.List<Integer>> map=new java.util.HashMap<>();for(int x:a){int r=x%m; if(r<0) r+=m; map.computeIfAbsent(r,k->new java.util.ArrayList<>()).add(x);}return map;}

Official Solution Code

static java.util.Map<Integer,java.util.List<Integer>> groupByRemainder(int[] a,int m){java.util.HashMap<Integer,java.util.List<Integer>> map=new java.util.HashMap<>();for(int x:a){int r=x%m; if(r<0) r+=m; map.computeIfAbsent(r,k->new java.util.ArrayList<>()).add(x);}return map;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.