今日已更新 317 条资讯 | 累计 37222 条内容
关于我们

标签:#algorithms

找到 62 篇相关文章

AI 资讯

Nine puzzle solvers, one browser tab, zero servers: a tour of classic search algorithms

I recently finished building a small suite of puzzle and game solvers that all run entirely in the browser — no backend, no API calls, no machine-learning models. You paste in a Sudoku, a chess position, or a crossword pattern, and the answer comes back instantly, computed on your own device. The fun part wasn't the UI. It was that each puzzle turned out to be a textbook excuse to reach for a different classic algorithm. Nine solvers, and I got to use constraint propagation, adversarial search, heuristic search, brute-force scanning, and plain old pattern matching — the stuff that shows up in an algorithms course and then, in most day jobs, never again. This is a tour of which algorithm fits which puzzle, and a few of the potholes I hit along the way. Everything here is vanilla JavaScript running in a Web Worker. The one design constraint: no server Before the algorithms, the rule that shaped all of them: it has to run client-side. That's a privacy choice (your puzzle never leaves the tab) and a cost choice (no compute bill), but it's also a fun forcing function. You can't lean on a beefy backend or a hosted model — you get one browser thread (well, a Worker thread) and whatever you can compute in a few hundred milliseconds. That budget is exactly why classic algorithms shine here. They're fast, deterministic, and small enough to ship as a script. Let's group the solvers by the technique each one leans on. Family 1: Constraint propagation Sudoku Sudoku is the poster child for constraint propagation. A cell that can only be one value forces that value; that in turn shrinks its neighbours' options, which forces more cells, and so on. Most "easy" and "medium" boards fall over from propagation alone (naked singles + hidden singles), and only the hard ones need a backtracking search on top. The nice property: the same engine that solves the board also powers the hint feature (find the next forced cell and explain why it's forced) and a uniqueness check — count solutions,

2026-08-29 原文 →
AI 资讯

What Is Precision Tracking Radar? A Developer’s Guide to Continuous Target Tracking

What Is Precision Tracking Radar? Precision tracking radar is an active radar sensing system designed to repeatedly measure a selected target and maintain an updated estimate of its state over time. For developers, the important distinction is that precision tracking is not simply repeated target detection. Detection answers: Is there evidence of a target in the current radar measurements? Tracking answers: Does this new measurement belong to an existing target, and how should that target state be updated? A practical precision tracking pipeline can be represented as: RF sensing → target measurement → detection → association → state update → continuous track → mission output That makes precision tracking radar a real-time data-processing system as much as an RF sensing system. A Practical Definition Precision tracking radar is a radar capability that combines repeated target measurements across time to maintain a continuous estimate of target position, motion or other relevant state information. The key word is continuous. A detector can operate independently on each radar update. A tracker has memory. It maintains information from previous measurements and decides how new observations relate to that history. From a software architecture perspective, tracking introduces persistent state into the sensing pipeline. Detection and Tracking Should Be Separate Services A useful radar architecture keeps target detection and target tracking logically separate. The detector processes current radar measurements. The tracker consumes target-related measurements over time. Conceptually: Radar measurement ↓ Detection ↓ Measurement object ↓ Association ↓ Track update ↓ Track state This separation helps developers understand where errors originate. If the detector produces unstable measurements, the tracker cannot fully repair them. If detections are stable but tracks switch between targets, the problem may exist in association. If sensor-relative detections are correct but missio

2026-08-29 原文 →
AI 资讯

How BitTorrent Turned Every Downloader Into a Server

Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is free and source-available on Github. Star git-lrc to help devs discover the project. Do give it a try and share your feedback. A couple of posts back we spent a while inside XOR distance , then used it to build Kademlia , the DHT algorithm that lets a network find anything without a directory. Kademlia: Algo That Turned XOR Distance Into a Network Athreya aka Maneshwar Athreya aka Maneshwar Athreya aka Maneshwar Follow Aug 26 Kademlia: Algo That Turned XOR Distance Into a Network # webdev # programming # beginners # algorithms 20 reactions Add Comment 6 min read I promised that algorithm shows up "under BitTorrent, IPFS, Ethereum." Today we cash that check. We're taking BitTorrent apart, piece by piece, and Kademlia is going to walk right back in through the side door. Also, fun fact before we start: a suspicious number of people on Reddit think Bram Cohen, the guy who wrote BitTorrent alone in Python in 2001, is secretly Satoshi Nakamoto. I'm not saying it's true. I'm saying that by the end of this post you'll understand why people keep saying it. The number that should not have been possible In 2004, a measurement firm called CacheLogic reported that BitTorrent alone was responsible for roughly 35% of all internet traffic. More than every other peer to peer network combined. More than the entire web. One protocol. Written by one guy. No company. No datacenter. No servers anywhere with "BitTorrent Inc" on the rack. That last part is the whole story. Every "normal" system you've ever worked on scales by throwing money at it: bigger box, more replicas, a CDN in front. BitTorrent had nobody to throw money at anything, so every hard problem, capacity, trust, scheduling, incentives, discovery, had to get solved inside the protocol itself . Problem 1: the client-server ceiling has a name Distributing a file in 2001 meant one server, one uplink, and every download eating

2026-08-28 原文 →
AI 资讯

Bitwise and Otherwise: Understanding XOR Distance

Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is free and source-available on Github. Star git-lrc to help devs discover the project. Do give it a try and share your feedback. I knew XOR. Truth tables, bit flips, the whole deal, nothing new there. Then I was reading some article about P2P networking and ran into the phrase "XOR distance" and just kind of stopped. XOR I know. Distance I know. XOR distance ? That's not a thing, that's two things wearing a trenchcoat. So I went and actually learned how it works, and it turns out it's one of those ideas that's simple once it clicks and mildly infuriating right up until it does. So let's do this properly. We're going to talk about bits, buckets, and why your node's "neighbors" have nothing to do with where they physically live. The one-line version XOR distance between two IDs is just: XOR their bits together, read the result as a number. That number is your "distance." Bigger number, farther apart. Smaller number, closer. That's it. That's the tweet. Obviously that's not satisfying, so let's actually build it up. Step 1: what XOR even does XOR (exclusive or) looks at two bits and asks one question: "do you two agree?" A B A XOR B 0 0 0 0 1 1 1 0 1 1 1 0 Same bits, you get 0. Different bits, you get 1. XOR is basically the "spot the difference" operator of computer science. Now take two IDs (in real systems these are 160-bit or 256-bit hashes, but let's use 4 bits so nobody has to squint): A = 1100 B = 1010 ---- 0110 (this is the XOR) Read 0110 as a plain binary number and you get 6. So distance(A, B) = 6. Congrats, you just computed an XOR distance by hand, you can put that on your resume now. Step 2: why we're even allowed to call this a "distance" Math is picky about the word "distance." For something to count as a proper metric, it needs three properties, and XOR happens to nail all three, which honestly feels like a happy accident but isn't. distance(A, A) = 0. An

2026-08-26 原文 →
AI 资讯

Leetcode 31: Next Permutation

Question : Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place and use only constant extra memory. Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. Example : 1,2,3 → 1,3,2 3,2,1 → 1,2,3 1,1,5 → 1,5,1 Idea : Scan from right to left and find the first element that is less that its previous. eg: 1 6 3 5 -> here it is 3. Let's name it as index. Again scan from right to left and find the first element that is greater than 3 and that's 5. Let's mark it as idx. 3.In this step we swap 3 and 5. Reverse elements from index+1 till the array length. Code: public void nextPermutation(int[] nums) { int index = -1; for(int i=nums.length-1;i>0;i--){ if(nums[i]>nums[i-1]){ index = i-1; break; } } if(index==-1){ reverse(nums,0,nums.length-1); return; } int idx=0; for(int i=nums.length-1;i>=index+1;i--){ if(nums[i]>nums[index]){ idx=i; break; } } swap(nums,index,idx); reverse(nums,index+1,nums.length-1); } void swap(int[] nums,int i,int j){ int temp =nums[i]; nums[i] = nums[j]; nums[j] = temp; } void reverse(int[] nums,int i ,int j){ while(i<j){ swap(nums,i,j); i++; j--; } } Code Explanation : We first initialize index=-1 and traverse backward to find the first one with i that satisfy the condition nums[i]>nums[i-1] . We assign this to index and break out of the loop. for(int i=nums.length-1;i>0;i--){ if(nums[i]>nums[i-1]){ index = i-1; break; } } Next step we are discussing a corner case. For example if the given array is 3,2,1 then we cannot find the element that satisfies the previous condition. So when the array is given in decreasing order we just reverse it and return. if(index==-1){ reverse(nums,0,nums.length-1); return; } Next iteration we are considering another variable idx and traverse backw

2026-08-24 原文 →
产品设计

Construyendo un recomendador de emparejamiento de expertos

La forma del problema Un directorio es una superficie: el miembro lo abre y adivina. Un recomendador es una superficie de empujar: el sistema propone y tiene que justificarse. La justificación es la parte difícil, y es donde vive la estadística. Tres restricciones hicieron esto distinto de un recomendador de contenido: El item es una persona con capacidad finita. Un hilo se le puede recomendar a diez mil personas. Un experto no. Una mala recomendación es cara de los dos lados. Quien pide desperdicia una petición, el experto desperdicia una hora, y los dos aprenden a ignorar la superficie. La afirmación tiene que ser checable. "Quizá te guste este hilo" no necesita evidencia. "Esta persona está un nivel adelante de ti en diseño de sistemas" sí. Recuperación: híbrida, fusionada con RRF Tres recuperadores independientes sobre el conjunto de expertos elegibles, fusionados con Reciprocal Rank Fusion: def rrf_fuse ( * ranked_lists , k = 60 ): """ Fusiona listas de ids rankeadas. El score depende solo del rank, nunca de la escala propia del recuperador, que es el punto: la similitud coseno y un conteo de hilos resueltos no son números comparables. """ fused = {} for lst in ranked_lists : for rank , key in enumerate ( lst ): fused [ key ] = fused . get ( key , 0.0 ) + 1.0 / ( k + rank ) return fused RRF es la primitiva correcta aquí por una razón que vale la pena decir: los recuperadores emiten cantidades incomparables. Uno regresa un coseno en [-1, 1] , uno regresa un conteo entero de hilos resueltos, uno regresa un delta de nivel de escalera. Normalizarlos a una escala común requiere supuestos sobre sus distribuciones que nadie tiene a este volumen de datos. RRF descarta las magnitudes y se queda solo con el orden, que es exactamente la información que sobrevive a una muestra chica. k = 60 es la constante estándar de la formulación original de Cormack et al. Aplana la cabeza: la diferencia entre el rank 1 y el rank 2 es 1/61 - 1/62 ≈ 0.00026 , así que un recuperador no pu

2026-08-24 原文 →
AI 资讯

Why Fixed-Window Rate Limiters Fail (And How to Fix Them with Math)

If you’ve ever built an Express API, you’ve probably reached for standard rate-limiting middleware to protect your login or payment endpoints from DDoS and brute-force attacks. Under the hood, most simple limiters use a Fixed-Window Counter . It’s easy to write: count incoming requests, and once the minute rolls over, reset the counter to zero. However, from a security and algorithmic standpoint, Fixed-Window counters have a massive blind spot. The Boundary Vulnerability (The 2-Second Spike) Imagine your endpoint allows a maximum of 100 requests per minute , resetting every full minute on the clock ( :00 ). Here is how an attacker bypasses that limit without breaking your rules: At 12:00:59 , the attacker fires 100 requests. (Allowed: 100/100 used). At 12:01:00 , the clock resets your counter back to 0. At 12:01:01 , the attacker fires another 100 requests. (Allowed: 100/100 used). To your server code, everything looks fine. But in reality, 200 requests slammed your backend within a 2-second window. In FinTech or authentication systems, that burst is more than enough to overwhelm payment gateways or run a successful credential-stuffing attack. The Algorithmic Fix: Sliding Window Counter To stop boundary spikes, we need a continuously sliding window rather than a rigid clock reset. Attempt 1: The Sliding Window Log (High Memory) You store a timestamps array (a Deque) for every user request and drop timestamps older than 60 seconds. While accurate, storing every single request timestamp takes $O(N)$ space. If your API receives millions of requests, your server memory dies instantly. Attempt 2: Sliding Window Counter (Optimal O(1) Math) Instead of keeping thousands of timestamps, we track only two integers : the request count of the previous window and the count of the current window . When a request arrives, we calculate an estimated request count by weighting the previous window based on how much time has passed in the current window: Estimated Requests = Current Cou

2026-08-23 原文 →
AI 资讯

Building a Fast Word Unscrambler: The Algorithm Behind Anagram Solving

I recently built WordScrambler, a free tool for unscrambling letters and solving anagrams, mostly out of frustration with existing tools being cluttered with ads or requiring sign-up just to see a result. Here's a quick look at the core technique behind how it works. The problem Given a jumbled set of letters (say, ucim), find every valid dictionary word that can be formed from some or all of those letters. The naive approach, generating every permutation and checking each against a dictionary, gets slow fast. A 7-letter input has 5,040 permutations; a 12-letter input has nearly 480 million. That's not viable for instant results. The signature trick The key insight: two words are anagrams of each other if and only if their letters, sorted alphabetically, produce the same string. For example: "listen" -> sorted -> "eilnst" "silent" -> sorted -> "eilnst" Both hash to the same signature. So instead of generating permutations, you can: Precompute a signature for every word in your dictionary and group words by signature. For a given input, generate the signature of the input (and its relevant sub-combinations, for partial-length matches). Look up matching signatures in a hash map, an O(1) lookup instead of a brute-force search. This turns "find every valid word from these letters" into a fast lookup problem rather than a combinatorial one, which is what makes results feel instant even against a large dictionary (WordScrambler checks against roughly 246,000 words). Handling partial-length matches Most real unscrambling needs go beyond "use every letter", people want every valid word of any length using a subset of the given letters. That means generating signatures for all relevant letter subsets (not full permutations, just subsets, which is a much smaller set) and checking each against the dictionary map. Try it You can play with the live version here: wordscrambler.online — it also shows word definitions and Scrabble/Words With Friends point values alongside each resu

2026-08-21 原文 →
AI 资讯

LeetCode 3116 (Hard) — binary search + inclusion-exclusion makes it easy

Full walkthrough: https://www.youtube.com/watch?v=vFuFA3ByCs0 LeetCode 3116 — Kth Smallest Amount With Single Denomination Combination. Here’s the trick everyone misses: Brute force (generate all multiples, pick k-th) fails because k can reach 2×10⁹. The real approach: Binary search the answer X Count valid amounts ≤ X using inclusion-exclusion Odd subsets add, even subtract (bitmask over coins) LCM via GCD, break when LCM > X O(n · 2ⁿ · log(k·M)) — passes cleanly. The 26% acceptance rate makes this look harder than it is. Once you see the count(X) monotonic trick, it clicks.

2026-08-21 原文 →
AI 资讯

Building a Location-Aware Discovery Engine: Why “Nearby” Isn't Just Distance

"Nearby" sounds like a simple feature. Calculate the distance between the user and every location. Sort by distance. Done. In practice, that's not enough. A useful local discovery engine has to understand more than geography. That's one of the problems we're tackling with LeeX. The basic version A traditional nearby query might look like: User location ↓ Calculate distance ↓ Sort ascending ↓ Return results If Restaurant A is 500 meters away and Restaurant B is 2 kilometers away, Restaurant A wins. But what if Restaurant A is permanently closed? What if Restaurant B is much more relevant to the user's category? What if Restaurant B is currently featured? What if thousands of people have recently interacted with Restaurant B? Distance alone doesn't capture usefulness. Our discovery model We're thinking about discovery as a combination of signals: Discovery Score = Distance + Relevance + Activity + Popularity + Featured status + Availability + User context The exact weighting can evolve. The important part is that proximity is one signal, not the entire algorithm. Distance still matters We don't want to ignore geography. For local discovery, distance is extremely important. A user looking for a restaurant probably cares whether it is: 500 m 1 km 2 km 5 km 10 km That's why LeeX can expose radius-based discovery. But distance should normally be combined with other information. Category context Suppose someone opens LeeX and selects: Restaurants The discovery engine should not treat every listing equally. The system already knows the user's current intent. That gives us a stronger query: Nearby + Restaurant + Open + Relevant rather than: Nearby + Everything Featured listings LeeX also has a promotion layer. Featured listings can receive additional visibility across relevant discovery surfaces. But promotional ranking needs to be handled carefully. A featured listing shouldn't necessarily make every other result useless. Instead, we can think of featured placement as an ad

2026-08-19 原文 →
AI 资讯

Algorithmic Patterns: The Ultimate Guide to Sliding Window

The Sliding Window pattern is one of the most vital algorithmic techniques for optimizing array and string problems. Instead of repeatedly processing overlapping subarrays - which leads to brute-force quadratic O(N^2) or O(N*K) complexities, the sliding window technique reuses previous computations to achieve linear time complexity $O(N)$ . In this guide, we will break down the mechanics, core variations, identification rules, real-world applications, and a curated list of 18 LeetCode problems with key solution strategies. 💡 What is the Sliding Window Pattern? A sliding window performs operations over a contiguous sub-segment (subarray or substring) of data structure. As the window "slides" across the array from left to right, elements entering and leaving the window are updated incrementally. Time Complexity Comparison Brute-Force Nested Loops: O(N^2) or O(N * K) Sliding Window Strategy: O(N) (each element is processed at most twice: once entering and once leaving) 🛠️ Recognition & Identification Rules When to Use Sliding Window Contiguous Input: The problem requires evaluating contiguous subarrays or substrings. Window Metric Criteria: You need to calculate statistics such as minimum/maximum length, sum, average, or character frequency targets. Monotonicity Property: Expanding the window strictly increases (or maintains) a target metric, while shrinking the window strictly decreases it (e.g., sum > K or at most K distinct elements over positive numbers). When NOT to Use Sliding Window Negative Numbers in Sum Constraints: If an array contains negative numbers and you are tracking a cumulative sum, expanding the window does not monotonically increase the sum. Use Prefix Sum + HashMap instead. Non-Contiguous Sequences: If the problem asks for subsequences (where elements do not need to be adjacent), sliding window fails. Non-Monotonic Metrics: If moving pointers does not give a predictable increase or decrease in your decision metric. 🔄 Fixed vs. Variable Length Slid

2026-08-17 原文 →
AI 资讯

How Garbage Collection Works: Let's Build One From Scratch

Introduction Your program keeps creating objects. Every function call, every loop iteration, every parsed JSON response produces new ones. You don't manually delete most of them. You've never written a line of code that says "free this memory now." And yet your application doesn't immediately exhaust all available RAM and crash. So who cleans everything up? The answer is a garbage collector, a piece of the runtime that runs quietly in the background, deciding what your program no longer needs and reclaiming that memory for future use. Most developers interact with it only when something goes wrong: an unexpected pause, a memory leak, or an out-of-memory error that shouldn't be happening. Understanding how it actually works turns those confusing moments into solvable problems. And as a bonus, the core algorithm is simple enough to build yourself. We'll do that by the end of this article. -- 1. The Memory Problem Every time your program creates an object, the runtime allocates a chunk of memory to hold it. A string, a dictionary, a class instance: they all need memory, and that memory has to come from somewhere. The somewhere is a region called the heap , a pool of memory that the program draws from as it runs. When you create an object, the runtime finds a suitable slot in the heap and reserves it. When that object is no longer needed, that slot should be freed so it can be used for something else. In languages like C, you manage this manually. You allocate memory when you need it, and you free it when you're done. This gives you control, but it creates two classic failure modes. Free memory too early and you have a dangling pointer, a reference to memory that's now being used for something else. Forget to free it at all and you have a memory leak: the program slowly consumes more and more memory until it runs out. Automatic memory management exists to eliminate these failure modes. Instead of relying on the programmer to track every allocation and release, the runti

2026-08-15 原文 →
AI 资讯

Token Bucket vs. Sliding Window: Building Rate Limiters That Actually Hold Under Load

Rate limiting sounds like a solved problem until you actually implement one and watch it fail in a way your load test didn't predict: legitimate bursts getting rejected, or a limiter that lets through 2x its stated limit at window boundaries. The failure modes are specific enough that it's worth working through the two dominant algorithms — token bucket and sliding window — with actual code, not just the diagrams. The problem with fixed windows The naive approach almost everyone reaches for first is a fixed window counter: pick a window size (say, 60 seconds), count requests in that window, reset the counter when the window rolls over. import time class FixedWindowLimiter : def __init__ ( self , limit : int , window_seconds : int ): self . limit = limit self . window_seconds = window_seconds self . count = 0 self . window_start = time . time () def allow ( self ) -> bool : now = time . time () if now - self . window_start >= self . window_seconds : self . window_start = now self . count = 0 if self . count < self . limit : self . count += 1 return True return False This is simple and cheap, and it's also broken in a specific, exploitable way. Say the limit is 100 requests/minute. A client can send 100 requests in the last second of window N, then another 100 in the first second of window N+1. That's 200 requests in roughly two seconds, well within the letter of "100/minute" as the code enforces it, but nowhere near the spirit of it. This is the classic boundary-burst problem, and it's the reason fixed windows get replaced once traffic is adversarial or bursty enough to find the seam. Sliding window: smoothing the boundary A sliding window log fixes this by tracking actual timestamps instead of a single counter, and counting how many fall within the trailing window at the moment of the request: from collections import deque import time class SlidingWindowLogLimiter : def __init__ ( self , limit : int , window_seconds : float ): self . limit = limit self . window_seco

2026-08-14 原文 →
AI 资讯

Monotonic Stack: The Matrix of Array Problems

The Quest Begins (The "Why") I still remember the first time I faced the “Next Greater Element” interview question. The array looked innocent enough, but every brute‑force attempt felt like I was hammering a nail with a sponge— O(n²) time, nested loops, and a sinking feeling that I was missing something elegant. I spent an hour sketching out the problem on a whiteboard, muttering, “There has to be a way to look ahead without looking back every single time.” That frustration is a rite of passage for many developers. We’re taught to think in terms of scanning left‑to‑right, but some array puzzles scream for a different perspective: we need to remember what we’ve seen in a way that lets us answer questions about the future elements instantly. Enter the monotonic stack—a deceptively simple data structure that turns those scary “look‑ahead” problems into straight‑line walks. The Revelation (The Insight) So what’s the secret sauce? A monotonic stack is just a stack that maintains its elements in strictly increasing or strictly decreasing order. Why does that help? Consider the Next Greater Element problem: for each index i , we want the first element to its right that’s larger than arr[i] . If we walk from left to right and keep a stack of indices whose next greater element we haven’t found yet, the stack will naturally be decreasing in value. Why decreasing? Imagine the stack holds indices [i₁, i₂, …, i_k] where arr[i₁] > arr[i₂] > … > arr[i_k] . When we encounter a new value arr[j] , any element on the stack that is smaller than arr[j] has just found its next greater element—namely arr[j] . We pop those indices, record the answer, and stop when we hit a value that’s not smaller (or the stack empties). Then we push j onto the stack. Because each index is pushed once and popped at most once , the total work is linear: O(n) . No nested loops, no repeated scans—just a single pass with a stack that does the heavy lifting. The same invariant works for other “first bigger/smal

2026-08-11 原文 →
AI 资讯

Budoucnost

AI jako partner, ne kalkulačka: člověk a AI při řešení Project Euler #185 srpna 2026 Co se stane, když člověk nepoužije umělou inteligenci pouze jako nástroj, který má dodat hotovou odpověď, ale jako partnera při řešení problému? Dnes jsme to vyzkoušeli na konkrétním problému z Project Euleru. Nechtěli jsme vytvořit nový algoritmus. Chtěli jsme zjistit, jak může vypadat skutečná spolupráce člověka a AI při hledání řešení. Experiment Vybrali jsme Project Euler #185 – Number Mind. Úloha obsahuje 22 šestnáctimístných sekvencí. U každé je uvedeno, kolik číslic je na správné pozici. Úkolem je najít unikátní šestnáctimístnou sekvenci, která splňuje všechna tato omezení. Na začátku jsme si stanovili jednoduché pravidlo: Nechceme pouze získat výsledek. Chceme společně hledat cestu k němu. První problém Naše první společná zkouška nedopadla podle očekávání. Ukázalo se, že jsme si pro experiment nezvolili ideální problém a postup. Místo toho, abychom se snažili chybu zakrýt, označili jsme první pokus jako neúspěšný a změnili postup. To se ukázalo jako důležitá součást experimentu. Chyba nebyla důvodem ukončit spolupráci. Byla informací pro další krok. Project Euler #185 U samotného problému jsme postupovali bez předem připraveného algoritmu. AI začala pracovat s kandidáty a jednotlivými řádky. Člověk průběžně sledoval strukturu problému a hledal jiný pohled. V určitém okamžiku přišel klíčový návrh: «„Nehledejme jen to, co je správně. Hledejme miny – čísla, která se nám nehodí.“» Tím se změnila orientace řešení. Místo hledání správných možností jsme začali systematicky vyřazovat možnosti, které nemohou být správné. Co přinesl člověk a co AI? Martin přinesl především: intuitivní pozorování, změnu perspektivy, rozhodování o směru dalšího řešení, pochybnosti a kontrolu jednotlivých kroků, myšlenku „min“. AI přinesla: rychlé zpracování velkého množství kombinací, strukturování hypotéz, systematické porovnávání, práci s omezeními, závěrečné ověření. Role se přitom během řešení nemě

2026-08-11 原文 →
AI 资讯

Union-Find: The Fellowship of the Sets

The Quest Begins (The "Why") I still remember the first time I saw LeetCode 323 “Number of Connected Components in an Undirected Graph”. I stared at the adjacency list, thought “I’ll just run a DFS from every node”, and coded it up in ten minutes. The solution passed the easy tests, but when the hidden test cases hit a graph with 10⁵ nodes and 10⁵ edges, my DFS started to choke—stack overflows, repeated visits, and a sinking feeling that I was brute‑forcing a problem that deserved a smarter tool. That night, after a few too many coffees, I stumbled upon a tiny comment in a discussion thread: “Union‑Find can do this in almost O(1) per operation”. My curiosity sparked like a power‑up in a retro arcade game. I had to know why this seemingly simple data structure could turn a nightmare into a breeze. The Revelation (The Insight) At its heart, Union‑Find (aka Disjoint Set Union, DSU) maintains a collection of elements partitioned into disjoint subsets. It supports two operations: Find(x) – returns the representative (root) of the set containing x . Union(x, y) – merges the sets containing x and y . The magic lies in two simple heuristics: Path Compression – when we walk up the tree to find a root, we make every node on that path point directly to the root. Future finds become flat, almost constant‑time. Union by Rank/Size – we always attach the smaller tree under the root of the larger one, keeping the overall tree shallow. Why does this give us near‑O(1) amortized time? Think of each Find as paying a small “tax” to flatten the path. The tax is paid only a few times per node before it becomes a direct child of the root. Over a sequence of m operations, the total work is bounded by O(m α(n)) , where α is the inverse Ackermann function—so slow‑growing it’s practically a constant for any realistic n . In plain English: every time we climb up, we leave a shortcut behind. The next climber benefits from that shortcut, and the structure keeps getting better. It’s like building

2026-08-11 原文 →
AI 资讯

The Matrix: Why Merge Sort Beats the Brute Force

The Quest Begins (The "Why") I still remember the first time I got hit with a sorting question in an interview. The interviewer slid a whiteboard marker across the table and said, “Sort this array of a million integers – and tell me why you chose your method.” My brain went straight to the trusty old bubble sort I’d learned in CS101. I started writing nested loops, feeling like Neo dodging bullets in slow motion, only to realize the runtime was creeping toward O(n²). After a few painful minutes, I could see the interviewer’s eyes glaze over – not because I was wrong, but because I was using a sledgehammer to crack a nut. That moment sparked a quest: What makes a sorting algorithm truly efficient, and how do I know when to reach for it? I dove into textbooks, blog posts, and late‑night YouTube deep dives. The answer kept pointing back to one algorithm that felt like discovering a hidden cheat code: Merge Sort . The Revelation (The Insight) So why does Merge Sort work so well? It’s not just about splitting and merging; it’s about guaranteeing that each level of recursion does a linear amount of work, no matter how the input is arranged. Think of an unsorted array as a messy pile of LEGO bricks. Merge Sort first divides the pile into two halves, then halves again, until each sub‑pile contains a single brick – which is, by definition, sorted. The magic happens in the merge step: we take two already‑sorted sub‑arrays and walk through them with two pointers, always picking the smaller front element and appending it to the result. Because each sub‑array is sorted, we never need to look back; we simply advance one pointer at a time. That walk is O(n) for the merge: each element is examined exactly once as it gets placed into the output array. Since we split the array log₂ n times (each level halves the size), we perform an O(n) merge at each of those log₂ n levels. Multiply them together and you get O(n log n) worst‑case time, with O(n) extra space for the temporary buffer

2026-08-11 原文 →