Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
Time complexity (Big-O) of merging two PriorityQueues

From the PriorityQueue Javadoc:

Implementation note: this implementation provides O(log(n)) time for enqueuing and dequeuing methods offer, poll, remove() and add; linear time for the remove(Object) and contains(Object) methods; and constant time for the retrieval methods peek, element, and size.

So, my question is, would the O(log(n)) time complexity hold up for merging PriorityQueues into one? Or would it be O(nlog(n)) considering the insertion? And would this change if merging more heaps?

These PriorityQueues are to represent heaps.

Something like this:

PriortityQueue<Integer> a = new PriorityQueue<>();
... add elements
PriortityQueue<Integer> b = new PriorityQueue<>();
... add elements
PriorityQueue<Integer> merged = new PriorityQueue<>(a.size() + b.size(), a.comparator()); // Assuming a and b have the same Comparator.
merged.addAll(a);
merged.addAll(b);
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

As you have pointed out the method add from the class PriorityQueue has O(log(N)) time complexity. If you look at the concrete implementation of the method addAll from the class PriorityQueue, you see the following:

public boolean addAll(Collection<? extends E> c) {
    if (c == null)
        throw new NullPointerException();
    if (c == this)
        throw new IllegalArgumentException();
    boolean modified = false;
    for (E e : c)
        if (add(e))
            modified = true;
    return modified;
}

So for each element in the collection passed as parameter, the method add is called. Therefore, the finally complexity will be O(Mlog(N)), where M is the number of elements of the collection passed as parameter and N is the number of elements of the priority queue.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda