Official account of the Polymathic Engineer newsletter, written by @franc0fernand0. Algorithms, distributed systems, and software engineering. Subscribe here:
Above a few dozen dimensions, a k-d tree becomes less efficient than a brute-force approach.
On a balanced tree, nearest neighbor search costs about O(2^k + log n). For a map containing one million points, this translates to traversing a path of 20 nodes and calculating a few dozen distances, against a million for the loop. But from k = 6 on, 2^k is larger than log n for any dataset you could store. At 20 coordinates, you need a million uniformly distributed points to reach the break-even point. At 30, a billion.
This is because data becomes sparse in high-dimensional spaces. The sphere around the target intersects almost every branch, leaving very little that can be pruned.
Few coordinates, static points, built from the median. Inside that, a k-d tree is hard to beat. Outside, you need a different way to partition the space.
Full article this week on @EngPolymathic
The 200th issue of the Polymathic Engineer is out 🎉
This week, we complete our discussion on nearest-neighbor search:
- Keeping the kd-tree balanced
- Three more queries, one traversal
- How fast is the search
- Where k-d trees fall short
Link:
https://t.co/HnAaoyZkN7
The 199th issue of the Polymathic Engineer is out. This week, we introduce kd-trees:
- One dimension is easy
- Why the obvious extension blows up
- Cycle through the dimensions
- Search and insert
- Nearest neighbor: descend, then backtrack
Link:
https://t.co/u0HU0Fmdty
The 198th issue of our newsletter is out.
We dig into how evaluate the performance of different ML models:
- The accuracy trap
- The confusion matrix
- Recall: catch all the positives
- Precision: trust the positives
- F-score
- ROC curve and AUC
https://t.co/qLmotnJnW3
Finding the weak spots of a graph takes a single DFS, not one DFS for every vertex.
An articulation vertex is a vertex whose deletion disconnects a graph. In a communication network, this corresponds to a server that, should it fail, could split the entire network into two separate parts.
The brute-force approach is simple but inefficient. You remove each vertex, perform a BFS or DFS to check whether the graph remains connected, and repeat this process for all vertices. With V vertices, that’s O(V(E + V)).
To derive a better algorithm, think of the DFS tree, instead. The tree edges connect vertices within a hierarchy. Back edges act like safety cables, linking vertices to their ancestors and keeping the graph connected even if some vertices were to be removed.
For each vertex, keep track of the nearest ancestor reachable via a back edge. If the nearest ancestor reachable from a vertex is its parent, then removing that parent isolates the corresponding subtree from the rest of the graph. If the root has two or more children, it is always an articulation vertex.
That tests every vertex with a single DFS run, in O(V + E).
The 197th issue of the Polymathic Engineer is out. We discuss complexity vs. flexibility:
- The straightforward version
- Letting clients bring their library
- Hooks: running client code between phases
- Listeners: notify, don’t wait
- Picking your spot
https://t.co/Bjax45n1ny
The 156th issue of the Polymathic Engineer is out. This time, we discuss what happens when you compute with floats:
- Adding floats
- Multiplying floats
- Comparing floats
Free to read here:
https://t.co/UkqC5niC6Y
The 195th issue of the Polymathic Engineer is out.
This week, we discuss how floating-point works:
- Why the point has to float
- Fractions in binary
- The IEEE 754 layout
- Normalized, denormalized, and special values
- Rounding
Read it here:
https://t.co/j8HPtoIg2E
The 194th issue of the Polymathic Engineer is out.
This week, we discuss how to build a cache:
- The API contract
- Memory alone is not enough
- Building an LRU cache
- When fresher data isn’t better: the LFU cache
- Implementation
Read it here:
https://t.co/Sn0vEA6qPX
Most backends talk to themselves like they're calling a stranger on the internet.
One user request turns into 5-10 hops inside the cluster, and every hop is JSON over HTTP. But you control and ship both sides. Nobody in there needs pretty field names, and you parse the same text again and again.
The question is just where the call comes from. Outside the cluster: REST. Between your own services: gRPC.
Read it this week on @EngPolymathic
The 193rd issue of the Polymathic Engineer is out.
This is the last article on API design:
- What RPC really is
- North-south vs. east-west traffic
- gRPC and Protobuf
- When performance tips the scale
- Where GraphQL fits
- Can one service offer both?
https://t.co/NNri6csPOt
This week in the 192nd issue of the Polymathic Engineer, we keep talking about APIs:
- Why a shared spec matters
- Generating code from the spec
- Validating live traffic
- Examples and mocking
- Versioning
- Catching breaking changes
link: https://t.co/2T80kGNyr8
The 191st issue of the Polymathic Engineer newsletter is out.
This weeks's article is about:
- API design and coupling
- What makes an API RESTful
- The Richardson Maturity Model
- Adopting an API standard
- Designing collections
- Error handling
Link:
https://t.co/tGs4rPvMbc
Your latency benchmark shows a great p99. It might still be lying to you.
The most popular way to measure latency is to wait for each response before sending the next request, which inadvertently coordinates with the system being measured.
Think about a garbage collection pause. The system freezes for 100 ms, and a real workload would queue up dozens of slow requests. But the benchmark just logs a single one and moves on.
Your p99 looks great, but it’s a lie. This is known as coordinated omission.
I wrote the second article in my latency series that also covers where all that variance comes from, from CPU caches to garbage collectors, how latency compounds across services, and a small ping tool you can run to see your own network’s tail.
Give it a read in this week’s issue of @EngPolymathic
The 190th issue of the Polymathic Engineer is out.
This week we keep discussing latency:
- Sources of latency
- How latency compounds
- Measuring without lying to yourself
- Hands-on: measure your own network’s tail
Read it here:
https://t.co/NRfDEtW5QL
The 189th issue of the Polymathic Engineer is out.
This week's article is about latency:
- What latency is
- Units and the limits of physics
- Why latency matters
- The laws of latency
- Latency is a distribution
Read it here:
https://t.co/4yAz7GV6M4
What’s the difference between a blocking and a 𝐧𝐨𝐧-𝐛𝐥𝐨𝐜𝐤𝐢𝐧𝐠 algorithm?
The best way to understand it is to start with blocking algorithms and continue with non-blocking ones.
A blocking algorithm does one out of two things:
- performs the action requested by a thread
- blocks the thread until the action can be done safely
If a thread (B) acquires the lock first and gets suspended, another thread (A) must wait for an arbitrary time.
A non-blocking algorithm does one out of two things:
- performs the action requested by the thread
- notifies the requesting thread that the action can’t be done
If a thread (B) acquires the lock first and gets suspended, another thread (A) gets turned down.
The 𝐝𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐜𝐞 between blocking and non-blocking algorithms is in the second step. A blocking algorithm stops A until the lock is released, while a non-blocking algorithm notifies A that access is rejected.
The most common way to implement a non-blocking algorithm is by implementing the data structure using CAS operations. CAS stands for “Compare and Swap”, and is an atomic operation. It compares the value of a variable to an expected value. If they do, it gives the variable a new value. Specific CPU instructions typically support CAS operations. Therefore, no synchronization or thread suspension is necessary.
Using a non-blocking algorithm in a concurrent environment brings two main benefits:
- No thread suspension. Thread B has a lower latency. It receives a response immediately and can decide what to do next.
- No deadlocks. Thread B does not wait for the lock to release, and there is no possibility that a deadlock occurs.
Simple algorithms can solve complex problems.
Sweep Line is one of them.
I used it mainly in computer vision apps, but it applies to many contexts.
It looks like a geometry trick, but it is mostly a way to process events in sorted order.
Let’s consider a shop and all the customers’ arrival and departure times in a day.
Suppose you need to calculate the maximum number of customers in the shop at the same time.
You can solve the problem by creating 2 events for each customer: one for the arrival and one for the departure.
After this, you can sort the events and map them on a line representing the time.
Then, you process the events in order according to their times.
While going through the events, you can keep a counter. The counter increases for each arrival and decreases for each departure. The largest value of the counter answers the problem.
The sweep line part runs in O(n) time, but the overall algorithm takes O(nlogn) due to the sorting step.
But this is always better than the brute-force solution, which would require comparing the events for each pair of customers in O(n²).
This was just a simple example. But the sweep line is a crucial technique in computational geometry and can solve complex problems like:
- find the closest pair of points in a set
- find the area of a union of rectangles
Hash maps and hash sets show up in interviews all the time.
The good news is that there are only two scenarios for using them.
1. Existence
Checking whether an element exists in an array is a linear-time operation.
Hash sets make it possible to do the check with amortized constant time.
Suppose you have an algorithm that needs to perform this operation M times.
With an array, the time complexity of this algorithm would be O(NM); with a hash set, only O(M).
2. Frequency
A hash map can be used to translate keys to integers. Each integer represents the occurrences of the corresponding key.
For example, suppose you want to verify if all characters in a string have the same frequency.
A hash map is the ideal data structure for counting character frequencies in linear time. You can check if the frequencies are unique with a single iteration over the map.