150 principais entrevistasFácil

Inserir intervalo

Guia detalhado e implementação de Python para o problema 'Inserir intervalo'.

Declaração do problema

Fácil

Você recebe uma matriz de intervalos não sobrepostos, onde intervals[i] = [starti, endi] representa o início e o fim do i-ésimo intervalo e os intervalos são classificados em ordem crescente por starti. Você também recebe um intervalo newInterval = [start, end] que representa o início e o fim de outro intervalo. Insira newInterval em intervalos de modo que os intervalos ainda sejam classificados em ordem crescente por starti e os intervalos ainda não tenham intervalos sobrepostos (mescle os intervalos sobrepostos, se necessário).

Intervalos de retorno após a inserção.

Escreva uma função insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]].

Restrições
  • 0 <= len(intervals) <= 10^4
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10^5
  • intervals is sorted by starti in ascending order
  • newInterval.length == 2
  • 0 <= start <= end <= 10^5

Exemplos

Example 1
Input
intervals = [[1,3],[6,9]], newInterval = [2,5]
Output
[[1,5],[6,9]]
Explanation

The new interval [2,5] overlaps with [1,3], so they are merged into [1,5].

Example 2
Input
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output
[[1,2],[3,10],[12,16]]
Explanation

Because [4,8] overlaps with [3,5],[6,7],[8,10], they merge to [3,10].

Need a Hint?
Considere usar estruturas de dados específicas de intervalos, como conjuntos ou heaps.
Edge Cases to Watch
  • Estruturas de entrada vazias
  • Entradas de elemento único
  • Grandes limites numéricos

Pronto para resolver?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Abrir no Editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Recursos Python recomendados

Expanda seu conhecimento com tutoriais interativos relacionados, folhas de dicas e comparações de código.