Programmazione competitivaFacile

Cerca nell'array quasi ordinato

Guida dettagliata e implementazione Python per il problema "Ricerca in array quasi ordinati".

Dichiarazione del problema

Facile

Scrivi una funzione search_almost_sorted(arr, target) che cerchi un valore target in un array quasi ordinato arr. Un array quasi ordinato è quello in cui un elemento che dovrebbe trovarsi nell'indice i in un array completamente ordinato può invece trovarsi nell'indice i-1, i o i+1. Restituisce l'indice in base 0 della destinazione, se trovato, altrimenti restituisce -1.

Vincoli
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i], target <= 10^9
  • All elements in arr are unique.

Esempi

Example 1
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 40)
Output
2
Explanation

40 is at index 2 (which is its correct position in a fully sorted version).

Example 2
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 90)
Output
-1
Explanation

90 does not exist in the array.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche per la ricerca e l'ordinamento come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.