Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguro

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
012345678901234567890123456789012345678901234567890123456789
Ayer
012345678901234567890123456789012345678901234567890123456789
Vistas totales
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Estructuras de datos básicas
Estructuras de datos básicas
Core ConceptsHow It WorksImplementationComplexity AnalysisPractice ProblemsReal-World Use
Debates

Guía de Estructuras de datos básicas · 5/6

Practice Problems

Por ahora, este capítulo solo está disponible en inglés.

These five problems are written for this guide. Each one is solved by choosing the right structure rather than by clever tricks. Try each before reading the approach.

Problem 1: Browser back and forward

A small browser starts at a home page. It supports three commands: visit url opens a new page, back returns to the previous page and forward undoes a back. Visiting a new page clears the forward history. Ignore back or forward when there is nowhere to go. Return the current page after all commands.

Approach: keep two stacks. back_stack holds pages behind the current one and forward_stack holds pages ahead of it. Going back moves the current page onto the forward stack; visiting clears the forward stack. Every command is O(1).

def browse(home, commands):
    current, back_stack, forward_stack = home, [], []
    for command in commands:
        if command.startswith("visit "):
            back_stack.append(current)
            current = command[6:]
            forward_stack.clear()
        elif command == "back" and back_stack:
            forward_stack.append(current)
            current = back_stack.pop()
        elif command == "forward" and forward_stack:
            back_stack.append(current)
            current = forward_stack.pop()
    return current

cmds = ["visit a", "visit b", "back", "back", "back", "forward", "visit c", "forward"]
print(browse("home", cmds))  # c

Problem 2: Requests in the last minute

A server logs request timestamps in seconds, in non-decreasing order. After each request, report how many requests arrived in the last 60 seconds, counting the current one (timestamps t - 59 through t).

Approach: a queue holds the timestamps still inside the window. On each new timestamp, append it and pop from the front while the oldest is older than t - 59. Each timestamp enters and leaves once, so the total cost is O(n).

from collections import deque

def recent_counts(timestamps, window=60):
    inside = deque()
    result = []
    for t in timestamps:
        inside.append(t)
        while inside[0] <= t - window:
            inside.popleft()
        result.append(len(inside))
    return result

print(recent_counts([1, 10, 59, 60, 61, 125]))  # [1, 2, 3, 4, 4, 1]

At t = 61 the window covers 2 through 61, so the request at 1 drops out. At t = 125 the window is 66 through 125 and only the current request remains.

Problem 3: First repeated order ID

Order IDs arrive as a list of strings. Return the first ID that appears for the second time, judged by the position of that second appearance, or None if all IDs are unique. Also report how many distinct IDs were seen before the answer.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorComplexity AnalysisCapítulo siguienteReal-World Use

Approach: a set remembers IDs already seen. Scanning left to right, the first ID that is already in the set is the answer. Each check and insert is O(1) on average, so the scan is O(n) instead of the O(n squared) of comparing every pair.

def first_repeat(order_ids):
    seen = set()
    for order_id in order_ids:
        if order_id in seen:
            return order_id, len(seen)
        seen.add(order_id)
    return None, len(seen)

print(first_repeat(["A7", "B2", "C9", "B2", "A7"]))  # ('B2', 3)
print(first_repeat(["X1", "X2"]))                    # (None, 2)

Problem 4: Hottest temperature in every window

Given hourly temperatures and a window size k, return the maximum temperature of every block of k consecutive hours.

Approach: a deque stores indices whose temperatures are in decreasing order. Before appending index i, pop from the back every index with a temperature less than or equal to the new one, because those can never be a maximum again. Pop from the front when an index slides out of the window. The front is always the maximum of the current window. Every index is pushed and popped at most once: O(n) total instead of O(n * k).

from collections import deque

def window_max(temps, k):
    candidates = deque()   # indices, temperatures decreasing
    result = []
    for i, t in enumerate(temps):
        while candidates and temps[candidates[-1]] <= t:
            candidates.pop()
        candidates.append(i)
        if candidates[0] <= i - k:
            candidates.popleft()
        if i >= k - 1:
            result.append(temps[candidates[0]])
    return result

print(window_max([12, 15, 11, 9, 14, 18, 13, 10], 3))  # [15, 15, 14, 18, 18, 18]

Problem 5: Group words by letters

Group words that are anagrams of each other, keeping groups in the order their first word appeared.

Approach: two words are anagrams exactly when their sorted letters are equal, so the sorted letters make a dictionary key. Python dictionaries keep insertion order, which gives the required group order for free.

def group_anagrams(words):
    groups = {}
    for word in words:
        key = "".join(sorted(word))
        groups.setdefault(key, []).append(word)
    return list(groups.values())

print(group_anagrams(["listen", "stone", "silent", "notes", "enlist", "tones", "cat"]))
# [['listen', 'silent', 'enlist'], ['stone', 'notes', 'tones'], ['cat']]

Summary

Undo and redo patterns call for stacks, sliding time windows call for queues, "have I seen this?" calls for a set, and "group or count by key" calls for a dictionary. When a nested loop compares every pair, ask whether a hash table or a monotonic deque can remember what the inner loop keeps recomputing.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.