oneby7

Foundations Standard library

592. Sort People by Age, Then Name

Easy

You are given two arrays of the same length, names and ages. Person i is called names[i] and is ages[i] years old.

Return the names of all the people, ordered by age from youngest to oldest. People of the same age are ordered by name, alphabetically.

Names compare letter by letter, and the first letter that differs decides. A name that is the start of a longer name comes first, so ann comes before anna. Two people can have the same name, and the answer holds one name per person.

Example 1

Input: names = ["mia", "leo", "ava", "zoe", "ben"] ages = [31, 25, 31, 19, 25]

Output: ["zoe","ben","leo","ava","mia"]

Explanation: Zoe is the youngest, at 19. Ben and Leo are both 25, so they go in name order, and so do Ava and Mia at 31.

Example 2

Input: names = ["sam", "sam", "al"], ages = [0, 7, 7]

Output: ["sam","al","sam"]

Explanation: The two people called sam are different people. The one aged 0 goes first. The other is 7, like al, and comes after al by name.

Example 3

Input: names = ["anna", "ann", "an"], ages = [40, 40, 40]

Output: ["an","ann","anna"]

Explanation: Everyone is 40, so the names alone decide the order, and a shorter name that starts a longer one goes first.

Check your understanding

Work out the answer for this input before you write any code.

names = ["eve", "bob", "amy"], ages = [30, 25, 30]

Constraints

  • 1 ≤ names.length ≤ 105
  • ages.length = names.length
  • 0 ≤ ages[i] ≤ 150
  • 1 ≤ names[i].length ≤ 20
  • names[i] holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.