Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

89
Vistas
Return certain element from Set based on ranking

I'm working on a project where I have a number of unique strings in a Set (or it could be an array). I'm trying to write a function that returns the string in that Set with the highest "value".

The "value" is determined by a hierarchy that contains a number of other strings, each residing within their own level. For example:

Level 1 (Highest) A1, A2, A3, A4 ...

Level 2 B1, B2, B3, B4 ...

Level 3 (Lowest) C1, C2,C3 ...

So for example, if the strings in my initial Set are [C2, C3, A2, B1], then I'd expect A2 to be returned. In situations where there is a "value" tie, then the first string could be returned.

One potential solution might be to iterate through that hierarchy structure (which would maybe be an array of arrays) starting at the highest level, then checking to see if the currently iterated-on value is contained in the Set. If it is, then that value could be returned.

Can anyone think of a better way to structure / accomplish this though? Thank you!

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Your general approach sounds reasonable, though a slightly better way would be to not have a hierarchy of arrays, but a hierarchy of sets. Checking whether an item exists in a Set is O(1), unlike an array, which is O(n). This way, the overall algorithm is O(n ^ 2), not O(n ^ 3).

for (const levelSet of hierarchy) {
  for (const str of inputStrings) {
    if (levelSet.has(str)) return str;
  }
}

Unless the level can be predicted from a string's structure without iterating through the hierarchy, I don't think there's a less complex solution.

If the level can be predicted without iterating - for example, if a string that starts with A is in the first hierarchy, and so on - it can probably be made less expensive by iterating over each string in the input instead, and not touching the hierarchy structure. (depending on the computation involved in determining the hierarchy level from a given string)

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda