Group Students by Grade - Problem

You are given a list of student records, where each record contains a student's name and their grade level. Your task is to group all students by their grade level and return a dictionary/map where:

  • The key is the grade level (as a string)
  • The value is an array of student names in that grade

The students within each grade should maintain their original order from the input list.

Note: Grade levels can be any string (e.g., "K", "1st", "2nd", "Senior", etc.)

Input & Output

Example 1 — Basic Case
$ Input: students = [["Alice", "10"], ["Bob", "9"], ["Charlie", "10"], ["Diana", "9"]]
Output: {"10": ["Alice", "Charlie"], "9": ["Bob", "Diana"]}
💡 Note: Alice and Charlie are in grade 10, Bob and Diana are in grade 9. Students maintain their original order within each grade.
Example 2 — Mixed Grade Formats
$ Input: students = [["Emma", "K"], ["Frank", "1st"], ["Grace", "K"]]
Output: {"K": ["Emma", "Grace"], "1st": ["Frank"]}
💡 Note: Kindergarten students Emma and Grace grouped together, Frank is alone in 1st grade.
Example 3 — Single Student
$ Input: students = [["John", "Senior"]]
Output: {"Senior": ["John"]}
💡 Note: Single student creates one group with one member.

Constraints

  • 1 ≤ students.length ≤ 1000
  • Each student record contains exactly 2 elements: [name, grade]
  • Student names are non-empty strings
  • Grade levels are non-empty strings

Visualization

Tap to expand
INPUTALGORITHMRESULTAlice, Grade 10Bob, Grade 9Charlie, Grade 10Diana, Grade 9Student Records[name, grade] pairs1Initialize empty hash map2For each student:• Extract name and grade• Add to grade group3Group students by grade• Grade 10: Alice, Charlie• Grade 9: Bob, Diana4Return grouped dictionaryGrade Groups Dictionary"10": ["Alice", "Charlie"]"9": ["Bob", "Diana"]Students grouped by gradeOrder preserved within groupsKey Insight:Hash map enables O(1) grade group lookup, allowing single-pass groupinginstead of searching through all existing groups for each student.TutorialsPoint - Group Students by Grade | Hash Map Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen