AI 资讯
Fifty seconds for half a megabyte: the optimisation that fixed the constant, not the order
A cryptography library had a bottleneck no test could see : encrypting half a megabyte took fifty seconds. Every test passed. They had been passing for months. The cause is a trap that keeps recurring: a correct, well-documented optimisation that fixes the constant and not the order — and whose comment, precisely because it is well written, convinces the reader the problem is already solved. What the code did Quipu renders encrypted data as a sequence of symbols. To do that it converts the whole message into a single huge integer and repeatedly divides it to extract digits, the same way you would convert a base-10 number to base 2 by hand. The code did not divide one digit at a time. It carried a sensible optimisation: divide by the largest power of the base that fits in a machine word, extracting nine digits per pass instead of one. The comment explaining it opened by saying that doing it one at a time would be quadratic , and then described the improvement. All true. And the result was still quadratic: extracting nine digits per pass divides the work by nine; it does not change how the work grows. That sentence — "doing it this way would be quadratic" — reads in the past tense, as if it described the previous state. It described the current one. The measurement, which is the only thing that says so Size Time Factor per doubling 64 KiB 0.79 s — 128 KiB 3.16 s ×4.0 256 KiB 12.6 s ×4.0 512 KiB 50.7 s ×4.0 Exactly four, three times running. That is textbook quadratic: every time the input doubles, the time quadruples. Extrapolating, ten megabytes would have cost about five and a half hours . And here is the point: a correctness test sees none of this . A slow algorithm produces exactly the same bytes as a fast one. The suite stayed green, and would have stayed green forever. The fix is two hundred years old Nothing had to be invented. Divide-and-conquer radix conversion is a classical algorithm: instead of peeling digits off one end, you split the number in half — div
开发者
I Compared 4 Dungeon Generation Algorithms. One of Them Never Works.
Four algorithms. Same grid. Very different dungeons. I implemented BSP trees, cellular automata, random walk, and room placement, ran each one 20 times on an 80x40 grid, and measured everything: connectivity, open space, path length, speed. The Results Algorithm Open Space Connected Rooms Path Length Speed BSP Tree 42.1% 100% 1.0 105 steps 0.88 ms Cellular Automata 55.8% 0% 15.2 78 steps 52.8 ms Random Walk 35.0% 100% 1.0 73 steps 274.7 ms Room Placement 18.9% 100% 1.0 81 steps 0.29 ms The big surprise: cellular automata never produces a connected map. Zero percent connectivity across 20 runs. Every single cave system has unreachable areas. The Maps BSP Tree (structured rooms, always connected) ################################################################################ ################################################################################ #####.........#####.............###################################....#......## #####.........#####.............##..........##############........#....#......## #####...........................##..........##############....................## #####.........#####.............##..........##############.............#......## #####.........#####.............##..........##############........#....#......## ##########.#######################..........##############........#....#......## ##########.#######################..........################..################## ######..........##################..........################..################## ######..........##################..........################..######..........## ######..........##################..........################..######..........## ######..........##################..........################..######..........## ######.............###############..........################..######..........## ######..........##.###############..........################..######..........## ######..........##.###############..........################..######..........##
AI 资讯
Finding charts that look like this one
Every charting tool eventually gets the same feature request: "show me other times this stock looked like this." It sounds like a lookup. It is not. The retrieval is the easy half. The hard half is that a correct implementation can still produce results that are quietly meaningless, and nothing in the code will tell you. Here is the method, and the failure modes worth knowing before you ship it. No claims about predictive power anywhere in this piece — the last section explains why that is a deliberate choice, not a hedge. The naive version, and why it fails immediately The obvious first attempt: take the last 30 days of closing prices as a query vector, slide it across history, compute Euclidean distance, return the closest matches. import numpy as np def naive_search ( history , query , k = 5 ): m = len ( query ) windows = np . lib . stride_tricks . sliding_window_view ( history , m ) dists = np . linalg . norm ( windows - query , axis = 1 ) idx = np . argsort ( dists )[: k ] return idx , dists [ idx ] Run this and you get garbage — but instructively specific garbage. Every match comes from whatever period had a similar price level . Query a stock trading at $180 and you get back the other times it traded near $180. The shape is irrelevant to the metric; the offset dominates it. Scale is the same problem in a different coat. A stock that moved 2% over the window and one that moved 40% can trace an identical shape, and raw distance calls them unrelated. Normalize per window, not globally The fix is to z-normalize each window independently: def znorm ( x , axis =- 1 , eps = 1e-8 ): mu = x . mean ( axis = axis , keepdims = True ) sd = x . std ( axis = axis , keepdims = True ) return ( x - mu ) / ( sd + eps ) Per-window is the load-bearing part. Normalizing the whole series once preserves the relative offsets you were trying to remove. Each candidate window has to be centered and scaled on its own terms before it's compared. There's a satisfying identity waiting here.
AI 资讯
Pangram Has Emerged as the Gold Standard of AI Detection. Should You Trust It?
Meet the AI police who can make or break careers—in publishing and beyond.
开发者
Zstandard einfach erklärt in 2 Episoden — Episode 1
Episode 1: Was in einer ZST-Datei passiertEpisode 1: Was in einer ZST-Datei passiertZST-Dateien begegnen uns immer häufiger bei großen Downloads, Softwarepaketen, Backups und Serverdaten. Sie sind oft deutlich kleiner als die ursprünglichen Dateien und lassen sich trotzdem sehr schnell wieder entpacken. Doch wie funktioniert das? Warum werden Dateien komprimiert? Eine Datei besteht aus Daten. Je mehr Daten sie enthält, desto mehr Speicherplatz wird benötigt und desto länger dauert ihre Übertragung. Kompression versucht, dieselben Informationen mit weniger Daten darzustellen. Beim späteren Entpacken muss daraus wieder exakt die ursprüngliche Datei entstehen. Nach dem Entpacken ist die Datei Bit für Bit identisch mit dem Original. Es wird nichts weggelassen und nichts vereinfacht. Wiederholungen benötigen unnötig viel Platz Betrachten wir diesen Satz: Kleine Katzen kuscheln auf kleinen Kissen, junge Katzen kuscheln auf bunten Kissen und alte Katzen kuscheln auf weichen Kissen.Die folgenden Teile kommen mehrfach vor: A = Katzen kuscheln auf B = KissenWenn wir die wiederkehrenden Textteile durch die Variablen A und B ersetzen, können wir den Satz kürzer darstellen: Kleine A kleinen B, junge A bunten B und alte A weichen B.Damit ist der Text noch nicht vollständig. Zusätzlich müssen wir speichern, wofür A und B stehen: A = Katzen kuscheln auf B = KissenAus diesen Informationen lässt sich der ursprüngliche Satz wiederherstellen. Jedes A wird durch Katzen kuscheln auf und jedes B durch Kissen ersetzt. Das ist bereits die grundlegende Idee der verlustfreien Kompression: Wiederkehrende Daten werden nicht jedes Mal vollständig gespeichert. Stattdessen werden sie einmal gespeichert und anschließend durch kürzere Verweise ersetzt. ### Zstandard verwendet keine Variablen Unsere Variablen A und B dienen nur dazu, das Prinzip verständlich zu machen. Zstandard versteht weder Wörter noch Sätze. Es weiß nicht, was Katzen oder Kissen sind. Für das Programm besteht eine Datei lediglich
AI 资讯
Implementing A* and RRT Motion Planning for Robotics
Implementing A* and RRT Motion Planning for Robotics Two classic planning approaches are A * and RRT (Rapidly-exploring Random Tree) . A* is particularly useful when the environment can be represented as a graph or grid. RRT is useful when planning in continuous or high-dimensional configuration spaces. A* Planning A* combines the cost already traveled with an estimate of the remaining cost. Conceptually: f(n) = g(n) + h(n) Where: g(n) is the cost from the start. h(n) estimates the cost to the goal. f(n) ranks candidate nodes. Grid Example S . . # . . . . . . # . . . . . . . . # . . # # # . # . . . . . . . G The planner explores promising cells while avoiding blocked cells. Python Implementation Skeleton import heapq def astar ( graph , start , goal , heuristic ): queue = [( 0 , start )] cost = { start : 0 } parent = { start : None } while queue : _ , current = heapq . heappop ( queue ) if current == goal : break for neighbor in graph [ current ]: new_cost = cost [ current ] + 1 if neighbor not in cost or new_cost < cost [ neighbor ]: cost [ neighbor ] = new_cost priority = new_cost + heuristic ( neighbor , goal ) heapq . heappush ( queue , ( priority , neighbor )) parent [ neighbor ] = current return parent RRT Planning RRT works differently. Instead of systematically exploring grid cells, it samples points and gradually grows a tree. x / x------x / S-----x x----x------G A typical loop is: Sample a random configuration. Find the nearest existing node. Steer toward the sample. Check collision. Add the new node if valid. Repeat until the goal is reached. RRT Skeleton for _ in range ( max_iterations ): sample = random_configuration () nearest = nearest_node ( tree , sample ) new_node = steer ( nearest , sample ) if collision_free ( nearest , new_node ): tree . add ( new_node ) tree . connect ( nearest , new_node ) if reached_goal ( new_node ): return extract_path ( tree , new_node ) A* vs RRT Property A* RRT Representation Grid/graph Continuous space Search Determinis
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,
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
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
AI 资讯
Kademlia: Algo That Turned XOR Distance Into a Network
Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is...
开发者
Learn Valid Parentheses, Reverse Linked List, and Tree Max Depth with Step-by-Step Visualization in DSA View View 👀👀
Hoi hoi! I’m @nyaomaru, a frontend engineer who struggles to make game sounds. 😿 Have you used DSA...
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
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
产品设计
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
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
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
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.
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
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
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