Sección DSAfácil

Búsqueda lineal

Guía detallada e implementación de Python para el problema de 'Búsqueda lineal'.

Declaración del problema

fácil

Escribe una función linear_search(arr, target) que tome una lista de números enteros arr y un número entero target. Escanea la lista de principio a fin y devuelve el índice basado en 0 de la primera aparición de target. Si target no está presente en la lista, devuelva -1.

Restricciones
  • 0 <= len(arr) <= 1000
  • -10^9 <= arr[i], target <= 10^9

Ejemplos

Example 1
Input
arr = [4, 2, 9, 1, 7], target = 9
Output
2
Explanation

The target 9 is found at index 2 of the list [4, 2, 9, 1, 7].

Example 2
Input
arr = [4, 2, 9, 1, 7], target = 5
Output
-1
Explanation

The target 5 is not present in the list, so we return -1.

Need a Hint?
Considere la posibilidad de utilizar estructuras de datos específicas de la búsqueda, como conjuntos o montones.
Edge Cases to Watch
  • Estructuras de entrada vacías
  • Entradas de un solo elemento
  • Grandes límites numéricos

¿Listo para resolver?

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

Abrir en el 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 recomendados de Python

Amplíe sus conocimientos con tutoriales interactivos relacionados, hojas de trucos y comparaciones de códigos.