arcbjorn

thoughtbook

RSS Feed

Sunday, July 21, 2024

Sort the People

Leetcode 2418 problem.

Given two parallel arrays of names and heights, return a new array of names sorted in descending order based on the corresponding heights.

Go

  • Time complexity: O(nlog(n))O(n*log(n)) - n is a length of an array
  • Auxiliary space: O(n)O(n) - n is a length of an array
import sort

type Person struct {
    name   string
    height int
}


func sortPeople(names []string, heights []int) []string {
    people := make([]Person, len(names))
    for i := range names {
            people[i] = Person{name: names[i], height: heights[i]}
    }

    sort.Slice(people, func (i, j int) bool {
            return people[i].height > people[j].height
    })

    for i, person := range people {
            names[i] = person.name
    }

    return names
}
Creative Commons Licence