Python Noções básicasFácil

Encontre o segundo menor elemento em uma matriz

Guia detalhado e implementação de Python para o problema 'Encontrar o segundo menor elemento em uma matriz'.

Declaração do problema

Fácil

Escreva uma função second_smallest(arr) que receba uma lista de inteiros arr e retorne o segundo menor elemento distinto. Se não existir nenhum segundo menor (todos os elementos são iguais ou a matriz tem menos de 2 valores distintos), retorne -1.

Restrições
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

Exemplos

Example 1
Input
arr = [3, 1, 4, 1, 5]
Output
3
Explanation

Sorted distinct values: [1, 3, 4, 5]. The second smallest is 3.

Example 2
Input
arr = [5, 5, 5]
Output
-1
Explanation

All elements are the same. No second smallest exists.

Example 3
Input
arr = [10, 20]
Output
20
Explanation

Two distinct values: 10, 20. Second smallest is 20.

Need a Hint?
Considere usar estruturas de dados específicas de arrays, 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.