and has 0 comments


Intro

Rarely, but consistently, people using regular expressions meet a scenario where a regular expression becomes incredibly slow. This is called "catastrophic backtracking". There are multiple solutions for this, but the one I am going to be talking today is atomic groups.

Definition

An atomic group has the syntax: (?>subexpression) . It instructs the regular expression engine that it should greedily match the subexpression and never backtrack. In other words, once it has matched, the engine discards the group's backtracking positions. This leads to a huge performance improvement, but also that if the pattern fails, the engine cannot re-enter the group to try an alternative match.
This is also called "non-backtracking subexpression" or "possessive". (possessive quantifiers like a++ are the same idea).
How backtracking works
  • Greedy quantifiers take as much as possible, then give characters back on failure.
  • Alternation tries branch 1, then branch 2, and so on.
  • Each choice point is saved on a stack. Failure pops the stack and retries.
  • Cost: failing matches can try every combination (exponential with nested quantifiers).

Examples

Pattern
Input
Result
Why
a+b
aaac
no match, tries 3 lengths of a+
backtracks
(?>a+)b
aaac
no match, tries 1 length
no give-back
a*a
aaa
match
a* gives one a back
(?>a*)a
aaa
no match
a* is locked
(?>ab|a)b
ab
no match
alternation locked on ab
(?:ab|a)b
ab
match
falls back to a

So atomic can change which strings match, not only speed!

When to use

  • Failing matches are cheaper: no retry of equivalent splits
  • Guards against catastrophic backtracking (^(a+)+$ on aaaa...!)
  • Makes it clear the part is decided and should not be revisited
  • Often a free optimization when the following token cannot start with the group’s characters (disjoint sets).

When NOT to use

  • It changes the result when the group needs to give back text:
    • (?>a*)a, (?>ab|a)b
    • (?>.*)foo never matches (.* eats everything); .*foo does
  • Short inputs: backtracking cost is negligible, atomic adds noise
  • Patterns with no ambiguity (no overlapping choices): nothing to prune
  • Wrong placement: atomic inside the loop vs around it
  • Does not replace a timeout (matchTimeout) or input length limits
  • Interpreter overhead: atomic constructs can be slower when they do not prune much
  • RegexOptions.NonBacktracking does not support atomic groups or lookarounds - choose one approach
  • Lookaheads and lookbehinds are already atomic in .NET; wrapping them adds nothing.

How to decide

  • Does the text matched by this group ever need to be given back for the overall match to succeed? If no, make it atomic.
  • Measure with the same regex options used in production (None, Compiled, NonBacktracking differ a lot).
  • Benchmark failing inputs, not only matching ones.
  • Fuzz old versus new pattern on random short strings from the relevant alphabet.
  • Keep the unit tests for allowed, blocked and long inputs.

Alternatives

  • Possessive quantifiers (Java, PCRE, not .NET).
  • RegexOptions.NonBacktracking (linear time, no atomic groups or lookarounds, set by option rather than pattern).
  • RegexOptions.Compiled or source-generated regex ([GeneratedRegex]).
  • Match timeout.
  • Rewrite for unambiguous alternatives.
  • Replace regex with a hand-written scanner.

References

and has 0 comments

TaskCompletionSource and TaskCompletionSource<T> are types that allow you to create an unbound Task, which means it’s not tied to a delegate. This gives you manual control over when and how the task completes. You can manually set the task’s result, or signal that the task has completed due to cancellation or an error.

What does it mean?

Well, I had this flaky integration test - flaky is a fashionable term for a test that randomly fails - that checked a semaphore system worked (the process had to only be allowed to start if there wasn't one already in progress). It used a Delay task, which would normally work, until something on the test machine made the code run faster or slower, and then it failed. It ran the process in a thread, then started the process again in another thread and expected it to return false.

So how did I solve it? I've set up a TaskCompletionSource, then I've mocked a service that was used after the semaphore was tested and created to SetResult for the underlying task, I ran the process, then awaited the task.

Something like this:

var source = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

_someRepo
  .Setup(r=>r.Insert(It.IsAny<Something>()))
  .Callback(()=>source.TrySetResult());

Assert.True(target.RunTheMethod())

await source.Task.WaitAsync(TestContext.Current.CancellationToken);

Assert.False(target.RunTheMethod());

// cleanup so that the methods don't run past the end of the test

No Delay needed.

The TaskCompletionSource classes expose these methods:

  • SetCancelled and TrySetCancelled
  • SetException and TrySetException
  • SetFromTask and TrySetFromTask
  • SetResult and TrySetResult

The "Try" versions just throw InvalidOperationException if the task is already in a final state (RanToCompletion, Faulted, or Canceled).

Quite simple, but versatile. Imagine that you want to run tasks not all at once or sequentially, but with finer control, like start tasks when a particular phase of another has finished or when capacity is available.

and has 0 comments

Interfaces are cool. They abstract behavior that can be implemented in a lot of different ways. One of the most used interfaces, abstracting the enumerable software pattern so successfully that we have internalized it before we ever knew what a software pattern was, is IEnumerable. It's just a series of things that you can get (enumerate) one after the other until you reach an end.

However, there are a lot of situations where knowing the total number of enumerable items helps, like when you want to project it into another data structure and you would like to know how large it should be. Have you ever considered how ToArray works on an IEnumerable? Well, think about it now. If the IEnumerable cannot be cast to ICollection - which does export a Count - or something similar, then a buffer has to be allocated, data copied, the buffer increased as more data is coming, then copying the data from the buffer into an array, now that we know its final size. It's basically doing ToList().ToArray()!

Enter TryGetNonEnumeratedCount, introduced in .NET 6 for the first time as an extension method on IEnumerable<T>. It does exactly what is says, try to get the count without enumerating:

  1. if it's an ICollection<T>, it sets the count and returns true
  2. if it's an Iterator<T>, it sets the count only if it's cheap - more to follow, this was new to me, too - and returns true if count>0
  3. if it's an ICollection, it sets the count and returns true
  4. sets the count to 0 and returns false

I used to do this by hand! I've had this kind of extension almost in every project I worked on. This is very useful.

But what is that Iterator? Apparently, Iterator<TSource> is an internal abstract base class defined inside System.Linq.Enumerable in the .NET runtime (in System.Linq).

It is the base class for the specialized iterator types that LINQ creates for deferred (lazy) operators such as Where, Select, Take, Skip, etc. Concrete derived classes include things like WhereIterator, SelectIterator, and many others.

Having worked on a LiNQ package for Typescript/Javascript, I can tell you that you can optimize a lot of these primitives by holding some meta information ready.

Iterator<T> implements both IEnumerable<T> and IEnumerator<T>. The GetCount(bool onlyIfCheap) method is an abstract method there, implemented differently by the various internal iterators.

This was an interesting dive in the iterator mechanisms in .NET.

and has 0 comments

Take a look at this line of code:

if (cmd.Def?.ColumnDef is not { } column) {
  return;
}

// do something with column

Do you understand it? Would you write something like that?

This is using the relatively new pattern matching behavior in C# and basically says "if ColumnDef is not a not null object that would otherwise be stored in a column variable, return". If your brain hurt at the "not a not null" part, you are not alone.

Normally I would have written this differently:

var column = cmd.Def?.ColumnDef;

if (column is null) {
  return;
}

// do something with column

There is a difference, though? Can you see it? Read the title of the post. Do you see it now?

The difference is in the type of the column variable in the two cases. The first matches anything that is not null to column, so column will be non-nullable there. In the second block, column will have the nullable version of whatever type ColumnDef was. So if ColumnDef is a string (reference type) column is string in the first case and string? in the second case. Damn you nullable aware C# ! If ColumnDef is an int, for example, column will be int in the first case and int? in the second.

The compiler may be smart enough to not warn about column being nullable after the is null check, but the type is already set in stone by then.

The result is that an AI will prefer the first syntax, as it is more correct and also shorter. Some devs might do that too (heck, there are people that *like* to code in Python). But what about reading that code? Ugh!

and has 0 comments

I was reviewing some code and I saw this class I had no idea existed: NativeLibrary.

In my case, I had a demo using different libraries that were doing similar things: parsing PostgreSQL code. However, some of them were wrapping the native pg_query library and were using different versions of it. The result were weird errors depending on which library was overwriting the file last.

Solution: use NativeLibrary.SetDllImportResolver, which worked nicely.

But what is this strange class? Introduced in .NET Core 3, NativeLibrary has several methods:

  • Load and TryLoad - loading native libraries
  • GetMainProgramHandle - get a handle to resolve exports from the entry point module
  • GetExport and TryGetExport - get the address of an exported symbol
  • Free - free a loaded native library
  • SetDllImportResolver - sets a callback for resolving native library imports from an assembly

In order to use a native library, you would do this in C#:

[DllImport("libraryName", ... some optional stuff..., EntryPoint = "myMethod_in_library"]
public static extern void MyMethod();

.NET is smart enough to look for libraryName in the format of the operating system: .dll for Windows, .dylib for MacOS, .so for Linux. However, the name is not enough, as DllImport expects a name that it resolves itself or a path.

You can provide a full or relative path. If you provide no path, the DLL must be in the current path at run time, unless the DLL is loaded by some other means. Be aware, however, that using a fully qualified path can introduce inaccuracy if the DLL is moved.

 If you want it to work for various operating systems, though, things get complicated. You could use something like this:

internal static class NativeMethods
{
    private const string LIB_NAME =
#if WINDOWS
        "somePath/mylib.dll";
#elif LINUX
        "someOtherPath/libmylib.so";
#elif OSX
        "bahMacOs/libmylib.dylib";
#endif

    [DllImport(LIB_NAME)]
    internal static extern int MyFunction();
}

But it's brittle and ugly. Moreover, this is something that only works for the code you control. If it's in a library you load from a NuGet or something, you're out of luck. Enter SetDllImportResolver in the NativeLibrary class.

static IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
  {
    var platformDependentName = GetLibraryName(libraryName);

    IntPtr handle;
    NativeLibrary.TryLoad(platformDependentName, assembly, searchPath, out handle);
    return handle;
  }

// then later
NativeLibrary.SetDllImportResolver(Assembly.GetExecutingAssembly(), DllImportResolver);

This works for platform dependent paths, but also for paths in the individual NuGet packages that I had in my project. It all depends on your implementation of the GetLibraryName method.

Note that this applies to all dll resolving, so you could conceivably use it to log things.

and has 0 comments

  I was reviewing code and I noticed an interesting idea. A method called DatetimeProvider.ForceNow which would return an IDisposable object. In a using block, you can force a specific time.

  Is it a good idea? Don't know yet, but I decided to talk about it The use of such method is almost exclusively about unit and integration tests. The IDisposable pattern assumes that you want to make sure you control the block where the time is set. But how is that different from just setting the time? The block is the unit test, after all. If you want multiple values, you just set those.

  I always love me a little IDisposable used as a block control mechanism, but I feel here it is misused. The biggest issue I see is that it introduces testing behavior in the DatetimeProvider. The normal way - and the one I think it's best - is that you inject an IDatetimeProvider and during tests you mock it.

  However, one must consider the advantages of such a mechanism, as well. You don't need to inject anything if you have a static DatetimeProvider. And then the only way to change its behavior for testing purposes is to add the methods to do that in it. It's lazy, but it works.

  Conclusion: I prefer the injection mechanism. It's general - doesn't apply only to time providers - it's clean, it promotes separation (and declaration) of concerns. In fact I would go so far as to call this ForceNow idea an antipattern.

Intro

In this post I will discuss my perspective on working as a software developer in the AI age and what it means. I will talk about how it was to look for a job first and how that changed, too. I don't mean it to be a rant, but it may become one in some places.

Looking

When I left my last job I did it without considering my next one. I just knew that it was pointless to keep working there, since it was all meetings and no code. I am a software developer, so what was I even doing in those meetings anyway? So I left. It also was a legacy code company, so I haven't learned anything remotely interesting in the last 6 years.

Then I took a break. I mean, who wants to search for a job in November, right? Waited for Christmas to pass, then I went on a vacation in Africa - it was nice, then I started to look for a developer job.

Shock!

Not that I didn't know, at an intellectual level, that things have changed. I try to keep up to date, at least at a consumer level of blogs and YouTube videos. I knew Covid and AI changed stuff, I just didn't understand the extent of the change.

For one, maybe one of the most important ones even if it doesn't sound so, is that recruitment is handled by HR people and technical people who have never seen the people they hire. Everything is remote. You talk to someone - with video if you're lucky, or on the phone, if you're not, then they pass you to another person who does the same in a different day, a different context. It's like a gauntlet of remote conversations. I could have Xi Jinping next to me telling me what to say and none would be the wiser.

Now, this is a consequence of Covid, not AI. There is an entire field of complaints about how AI does the initial screening based on resumés created by other AIs and so on. That was inevitable and I don't intend to talk about that. The problem I am explaining is that people who don't meet people are evaluating people. Even when you sign the contract you do it digitally, you don't shake anyone's hand, you just ... plug in.

What does it mean? It means people can - more than before - behave like keyboard trolls. They can lie to you with impunity, trick you or being total assholes. What are you going to do? Smash the monitor? Tell them off? That's why I went through several interviews for a company that - as I later found out from one of the employees - had a hiring freeze and were only permitted to hire from India. Why? I have no idea. I think they asked me whatever they wanted to know and were happy someone educated them. There is absolutely no emotional connection between you and the people who hire you, there is no opportunity to "get a feel" for a person unless what you get from the upper body video and whatever passes through each other's headphones.

Then there is the technical interviews. Before all of this, in the before times, people had no idea how to hire technical people. Nowadays, they REALLY have no idea, because they don't actually understand what they are hiring them for anymore. What value does a coding task have if a machine can do it already? Before it was things that you could just look up on Google and get the information on how to do it, if not a code snippet. Now you just ask any decent model to write the thing for you and it spews out exactly what they wanted.

As for what they ask you? High performance distributed cloud applications using microservices. The what?! It's like they all learned to ask for the same thing. The joke is that their applications are rarely so distributed, they are cloud applications in the sense they are served in Amazon Cloud instead of on their machines and they are almost never high performance. As for microservices? They are done as often and as right as Scrum is. I will leave it at that. All that in a climate where trendsetters are moving away from microservices.

It was basically a crap shoot, and if you are reading this while searching for a job, first of all condolences. Second of all, it's all luck. You obviously find some holes in your education that you need to fill or have to learn some new things, but what you know barely matters in this process. Thing is, it used to matter and who you were as a person also used to matter. Now all that is out the window.

Finding

As it often happens with me, I failed getting hired by every company I was reasonably confident I did well in the interviews for and got hired by the one where I was certain I had failed.

It's a nice company, too, with nice people. It does have microservices... somewhere, but I am not working on those.

When I started searching, I was looking for a decent job - money was not really an issue - in an office. I don't love people that much, but after years of doing everything remote, I kind of miss them. In the before times, one would dream of a job where you didn't have to spend 3 hours preparing for and commuting per day. Now, good luck finding one where they ask you to come to the office.

This company reluctantly and kind of apologetically said they require people to come to the office one day per week. Kind of low, but OK. Also, I can be hired as a contractor or employed, but they prefer contractor. I was kind of tired of doing invoices and stuff, but OK. And if I am a contractor, I don't have to come to the office at all.

So basically I am doing remote again!

Working

So how is work? Well, there is a lot of AI. You can ask AI about anything. Even here there is a framework that increasingly moves toward "the box". I talked about this before. It's the artificial employee. Instead of you interacting with it, it interacts with you. It's a subtle distinction, but it's the difference between a person being assigned to a task and getting help from an AI assistant and the AI working on the task itself and occasionally asking you for help with a review or question it needs answering.

We're not there, yet, though, so I asked if we were doing Scrum or Kanban. Scrum, obviously. Only the manager plans the sprint and if you don't have anything assigned to you, you can pick whatever there is in the backlog. How is that Scrum? Don't know. But frankly, I didn't mind. I came with new employee energy, took all the unassigned tasks, put the AI to work on them, reviewed them, came with advice, refined the results, created the PR and boom!

You used how many tokens?!?!

Yeah, that happened. After boasting how AI first they were, they were also kind of shocked someone used AI to the max. OK, maybe I exaggerated a little, you know, but I was experimenting.

You see, working with AI is kind of like becoming the mentor of a junior developer with encyclopedic knowledge. It knows how to do individual things, but it doesn't know why. And you can use different agents, but the balance comes as "can you be clear enough so that a cheap agent does the job or can you afford the expensive one who understands nuance?".

Personally, I am on a fence with this. I prefer to use the best engine at all times, even if I waste a lot of money, rather than have to refine the work of a lesser model or be afraid it messed something up or missed something or spend the same amount of money because I had to retry a few times. But I am also against wasting resources. I think this will become moot soon, as models will all move towards Mixture of Experts mode and make the choice themselves.

Anyway, I haven't written one line of code in a month. I am telling the AI what to do, I am reviewing, and it's good enough. I even learn new things from it, too. The bottleneck has changed, it's not the code anymore, it's the attention and the code reviews. Yeah, yeah, attention is all I need, ha ha!

But this also means I have to change. For example I did something today that would have felt idiotic a year ago. I took all of my Pull Requests - the one approved and merged, mind you - and started looking at the code to see if there is anything I can learn or understand from it. It's "my" code, but I needed a second pass - well, a tenth pass - to make the reviewing about learning rather than about finding issues or improvements.

Sometimes it feels like magic. You tell the AI "hey, I don't understand what this guy means in the Jira task!" and the AI goes "Oh, it's about this part of the project, he wants to do this, and that can be done via this method and I wrote the code and what do you think?" or you tell the AI to take the current branch, understand the independent changes and their purpose, then create different branches for each, then generate a PR with a description of what they contain and what they are doing. There is no need to use git or GitHub. It's easy to get carried away and forget that this level of AI assistance requires a scan of the entire application. Also that it doesn't mean it knows more than you or that you don't have to understand and learn that shit, quite the contrary.

It feels like... SQL, to be frank. There you also have to write declarative code and optimize on cost.

Even if you use it all the time, you must never trust the output of AI, just like you would not trust the output of your colleagues when you review their code (he he!). Sometimes it's easy to say "hey, that guy can code, I can just approve his stuff", but if they had a bad day, you just approved bugs.

That is why, just like in the development cycle design -> implement -> test -> refactor (yeah, I am standing by it, as I did for the last 30 years. If you don't like it, budgeting department or middle manager, then that's on you. Refactoring is not a dirty word!) now we must consider a personal development cycle understand -> prompt -> implement -> learn.

The AI infrastructure adapts, as well. You start with skills and MCP, but at every task that you use it for, you have to ask yourself: can I build a permanent tool that will repeat this work rather than ask the AI? It's easy to tell the AI to do things, but if it needs to reason every time to do something repeatedly, that's on you.

Structure

The structure of the planning and implementing tasks has also changed dramatically. If in the past people would avoid refactoring because they didn't trust their own test suites and were afraid of bugs introduced by small manual mistakes in the process, now you can just instruct the AI to do a full refactoring, only checking what they did and what they missed. It maintains the testing suite, too.

Projects that were unimaginable before now become options. I don't think management caught up to this yet, but they'll get there.

I feel, and it's a feeling I have to admit, that creativity gets a boost with AI. Even if your shop refuses to change their ways and just go on writing new features and never refactoring or improving or innovating, they will be pushed out by the other who do. The monopolies relying on no one making the effort to write software from scratch that performs the same function as their crappy tech indebted dinosaur will crumble. Is that good for developers? I think so.

Conclusion

I keep learning, which is cool, and I am in that nice euphoric place that decent jobs give to newly starting people. I hope I don't sour on it too soon.

To mitigate that possibility, I am planning large research projects, starting with understanding the architecture of the entire company code, how it connects, how it works, then drill down. I want to make it an interactive app.

AI can help a lot with focused learning. Instead of trying to learn everything, you can ask the computer to do something then learn from what it did. It can also summarize large swaths of information, allowing you to drill down and up from any level.

I think the future of AI is bright. It's the humans that will have problems. But can we adapt? That's the big question. We've always managed to do it before, so maybe we will continue to do so.

I am glad I get to do the thing I love, coding, and with tools that improve my speed tenfold. But I can never allow myself to get complacent. If a lot of my output is now done by machines, I must redirect the mental capacity that previously generated that output to something else, equally if not more valuable.

Here is for a hopeful conclusion!

Requirement

You are on a web page, using JavaScript, and have a reference to an element node. And you want to select the immediate children of that node using the general syntax used by querySelectorAll, maybe with some extra constraints. What do you do?

Failed attempt

The CSS syntax for children of a node is using the greater-than character, something like this: #parentNode > *, but as soon as you try in JavaScript parentNode.querySelectorAll('> *') you get an error: '> *' is not a valid selector.. That doesn't work...

Solution

The solution is using the :scope pseudo-class. In a "traditional" selector, it represents the element the method is called from, in our case #parentNode. The code becomes parentNode.querySelectorAll(':scope > *') and now it all works. In simple CSS it makes no sense as it just works exactly like :root.

:scope is widely supported in this particular scenario, since Chrome 27 and Firefox 32 and Safari 7, meaning it was completely supported at the end of 2014.

But it also has a secondary use, as a stand-in for the scoped element in the @scope CSS at-rule, which is something newly available in 2025 and frankly, pretty sweet. You can follow the documentation and even use it in your web sites made for modern browsers, but that's not in the... scope... of this blog post, though.

Hope that helps!

  Not that I am a CSS guru, but it was surprising for me that I didn't know about the :is pseudo selector (and the very similar :where), especially since I have been heavily using :has.

  But wait a minute, you will say, why do I need a selector for being something? Don't all selectors do that by default? The answer is that these pseudo selectors support lists of selectors, thus acting like a kind of context block for CSS.

  Imagine that you want to style the icons in a container in a certain way, but the icon elements are both span and div with :after content and actual img. A classic CSS rule would look like this:

.container div[data-icon],
.container span[data-icon],
.container img {
 ...
}

but with :is this gets significantly simple:

.container is:(div[data-icon], span[data-icon], img) {
 ...
}

/* OR */

.container is:([data-icon]:is(span,div), img) {
 ...
}

The only thing to clarify is the difference between :is and :where, because they apparently work the same. Well, :where does not add specificity, while :is does add the specificity of the most specific selector inside it. .container a:is([data-icon],.myclass:hover) has the same specificity as .container a.myclass:hover while .container a:where([data-icon],.myclass:hover) has the same specificity as .container a.

Both :is and :where have been available for Chromium and Firefox (versions 88 for both) since early 2021, so they are relatively new but well covered.

A few days ago I saw several bugs introduced by a well meaning dev who wanted to heed the UIEvent.which deprecation announcement and use the .key property instead. But even if .which is deprecated - that's actually untrue for every browser out there at the moment - the implementation of replacement properties is not fully supported.

First, there is the complication of the effect of the Shift key on the .key property. If you press Shift+3, then .which will be '3' and .key will be '#' and, for Shift-A, 'a' and 'A'. And that happens on a standard United States keyboard layout. For other layouts it's different. There is the concept of a Dead key, which you press on some keyboards to get a character with the press of another key, like adding an accent. In that case the .key property reads 'Dead'!

Second, the .key property is not always there. For example the Edge (and probably Chrome) code to autofill fields is simulating typing (with isTrusted true) without specifying a key. This may not even be a bug, considering that Autofill is not supposed to depend on a specific keyboard.

Then there is a .code property that is supposed to show the physical key that was pressed on the keyboard, but it's only fully implemented in Edge and Safari. And you don't get '1', but 'Digit1' and 'KeyA' instead of 'a' and even stuff like 'Comma'.

And there are other obsolete, deprecated or never fully implemented properties on events: charCode, keyCode, keyIdentifier and so on.

So be careful on how you handle key events. It's a mess.

Intro

  At the moment I am looking for a job, so in my research into coding test platforms, the problems that cannot be solved with just a little thinking and some loops are 80% covered by just 8 categories of problems:

  1. Optimization with overlapping subproblems (coin change, longest increasing subsequence, knapsack variants, matrix chain) - solved with Dynamic Programming (memoization/tabulation).
  2. Pathfinding, connectivity, or level-order processing in grids/graphs (number of islands, shortest path in maze, rotten oranges) - solved with Graph Traversal: BFS and DFS.
  3. Hierarchical data processing (tree diameter, in order traversal, BST validation, lowest common ancestor) - solved with Tree Traversals and Properties (pre/in/post-order, level-order, recursion/DFS on trees).
  4. Exhaustive search with pruning (permutations, subsets, N-Queens, sudoku solver, word search) - solved with Backtracking.
  5. Local optimal choices that work globally (jump game, task scheduler, fractional knapsack) - solved by Greedy Algorithms.
  6. Efficient "top-k" or priority processing (merge k sorted lists, kth largest element, task scheduler with cooldown) - solved with Heaps / Priority Queues.
  7. Efficient union of sets / cycle detection in graphs (redundant connection, number of provinces, Kruskal's MST) - solved with Union-Find (Disjoint Set Union) with path compression & union-by-rank.
  8. Searching in sorted/monotonic spaces (search in rotated sorted array, minimum in rotated array, binary search on answer for capacity problems) - solved by Binary Search (advanced variants).

Bonus:

This post will be about shortest path problems when the weights may be negative: Bellman-Ford and Floyd-Warshall.

When to use

Dijkstra (see the Heaps post) is fantastic when all weights are non-negative, but as soon as negative edge weights appear (currency arbitrage, flight prices with refunds, or certain graph modeling tricks) Dijkstra fails.  

Bellman-Ford solves the single-source shortest path problem with negatives and can detect negative cycles.

  • single source, possible negative edges, need to detect negative cycles (O(V·E) is acceptable).

Floyd-Warshall solves the all-pairs shortest path problem in one shot and also detects negative cycles.

  • dense graph (E ≈ V2), need distances between every pair of nodes, V ≤ 400 (O(V3) is fine).

Typical problems: cheapest flights with refunds, arbitrage detection, transitive closure, "find the city with the smallest number of reachable neighbors within a distance threshold".

Theory

Relaxing an edge means that if the path from source to a destination node is shorter if doing it via an intermediate node, we update the estimate for the distance from source to destination. The term comes from the fact that the distance to a node is an upper bound (a "relaxed" estimate) on the true shortest-path distance. When we find a better path, we relax (lower) that upper bound. The operation never increases the estimate, and after enough relaxations the estimates become exact shortest-path distances.

Bellman–Ford, Dijkstra, A*, Johnson's algorithm and others use edge relaxing. 

Bellman-Ford

The core idea of the algorithm is to relax every edge |V|−1 times. After that, any further relaxation means a negative cycle exists.

Implementation:

int[] ShortestPath(int n, int[][] edges, int src)
{
    const int halfMax = int.MaxValue / 2;
    int[] dist = new int[n];
    Array.Fill(dist, halfMax);
    dist[src] = 0;

    // Relax |V|-1 times
    for (int i = 0; i < n - 1; i++)
    {
        foreach (var e in edges)
        {
            int u = e[0], v = e[1], w = e[2];
            if (dist[u] != halfMax && dist[u] + w < dist[v])
                dist[v] = dist[u] + w;
        }
    }

    // Check for negative cycle
    foreach (var e in edges)
    {
        int u = e[0], v = e[1], w = e[2];
        if (dist[u] != halfMax && dist[u] + w < dist[v])
            return null; // negative cycle reachable from src
    }

    return dist;
}

int[][] edges = [
    [0, 1, 5],
    [1, 2, -3],
    [0, 2, 10]
];

var dist = ShortestPath(3, edges, 0);

Console.WriteLine(dist != null
    ? string.Join(", ", dist)   // 0, 5, 2
    : "Negative cycle detected");

Complexity

  • Time: O(V*E)
  • Space: O(V)

The O(V*E) time bound follows directly from |V| passes over the edge list, and the space is O(|V|). In practice the algorithm often converges early (no updates in a pass), but the worst-case analysis guarantees correctness even on adversarial inputs with negatives. This combination of dynamic-programming clarity, negative-weight tolerance, and built-in cycle detection makes Bellman-Ford the theoretical foundation for many more advanced shortest-path algorithms (Johnson’s algorithm, difference constraints, etc.).

The Bellman-Ford algorithm solves the single-source shortest-paths problem on a directed graph by exploiting the optimal substructure of shortest paths via dynamic programming. After the k-th iteration, every distance value in the array is already the shortest possible path from the source that uses at most k edges.

Each full pass over every edge checks whether there is a better way to reach any node by coming through one additional edge. Because the previous pass already had the best answers using up to k-1 edges, this new pass simply improves the answer to the best version that now allows one more edge.

A simple path in a graph can never use more than n-1 edges; if it did, it would have to visit the same node twice and therefore contain a cycle. That means after exactly n-1 complete passes, the array already holds the true shortest paths from the source to every reachable node, provided there are no negative cycles.

One final extra pass is then performed. If any distance can still be made smaller, it means there must be a negative cycle reachable from the source, because otherwise the distances would already be optimal and no further improvement would be possible. This extra check is what gives Bellman-Ford its ability to detect negative cycles, something Dijkstra cannot do.

Floyd-Warshall - shortest path

Floyd-Warshall starts with a table that only knows the direct edges between every pair of nodes (infinity for no connection). Then it goes through every possible intermediate node, one by one, and for every possible pair of start and end nodes it updates the table if the path through there becomes shorter.

Here is the implementation:

int[][] AllPairsShortestPath(int n, int[][] edges)
{
    const int halfMax = int.MaxValue / 2;
    var dist = new int[n][];
    for (var i = 0; i < n; i++)
    {
        dist[i] = new int[n];
        Array.Fill(dist[i], halfMax);
        dist[i][i] = 0;
    }

    foreach (var e in edges)
    {
        int u = e[0], v = e[1], w = e[2];
        dist[u][v] = Math.Min(dist[u][v], w);
    }

    for (var k = 0; k < n; k++)
        for (var i = 0; i < n; i++)
            for (var j = 0; j < n; j++)
                if (dist[i][k] != halfMax && dist[k][j] != halfMax)
                    dist[i][j] = Math.Min(dist[i][j], dist[i][k] + dist[k][j]);

    // Negative cycle check
    for (var i = 0; i < n; i++)
        if (dist[i][i] < 0)
            return null;

    return dist;
}

int[][] edges = [
    [0, 1, 5],
    [1, 2, -3],
    [0, 2, 10]
];

var distMatrix = AllPairsShortestPath(3, edges);
Console.WriteLine("0 -> 2: " + distMatrix[0][2]); // 2

Complexity

  • Time: O(V3)
  • Space: O(V2)

The Floyd-Warshall algorithm solves the all-pairs shortest-paths problem on a directed graph by using dynamic programming to consider every possible intermediate node in a systematic way. It begins with a distance table that contains only the direct edge weights between every pair of nodes. Then, for each potential stopping point in the graph, it checks every possible pair of start and end nodes and updates the recorded distance if routing through that stopping point produces a shorter total path.

Because it exhaustively tries every possible intermediate node exactly once, and does so in an order that builds upon previously discovered shorter routes, the final table contains the true shortest path between every pair of nodes, assuming no negative cycles exist. An extra check at the end looks for any negative values on the diagonal of the table to detect whether a negative cycle is present anywhere in the graph. This triple-loop approach is simple , turning what would be many separate single-source problems into a single computation.

Comparison

Best for

  • Bellman-Ford: Single source, sparse graphs
  • Floyd-Warshall: All-pairs, dense graphs (V≤400)

Detects negative cycles

  • Bellman-Ford: Yes (reachable from source)
  • Floyd-Warshall: Yes (anywhere in graph)

Time

  • Bellman-Ford: O(V*E)
  • Floyd-Warshall: O(V3)

Space

  • Bellman-Ford: O(V)
  • Floyd-Warshall: O(V2)

Typical problems:

  • Bellman-Ford: Cheapest Flights variants, arbitrage
  • Floyd-Warshall: City with smallest number of neighbors within distance., Evaluate division (variants), transitive closure

Code simplicity

  • Bellman-Ford: Medium (edge list)
  • Floyd-Warshall: Very simple (matrix)

Notes

  • Dijkstra is faster when no negatives
  • For Bellman-Ford, early termination after no updates in a pass is a nice optimization (still O(V*E) worst case).
  • Floyd-Warshall is perfect when V ≤ 400; beyond that you usually need Johnson’s algorithm (Bellman-Ford + Dijkstra).
  • Negative cycle detection: Bellman-Ford only detects cycles reachable from the source; Floyd-Warshall catches any cycle in the graph.
  • Edge cases: self-loops, disconnected components, negative self-loops (instant cycle).

Conclusion

Bellman-Ford and Floyd-Warshall together solve the entire family of shortest-path problems that Dijkstra cannot touch: any graph with negative edge weights, negative cycle detection, and all-pairs shortest paths.

Intro

  At the moment I am looking for a job, so in my research into coding test platforms, the problems that cannot be solved with just a little thinking and some loops are 80% covered by just 8 categories of problems:

  1. Optimization with overlapping subproblems (coin change, longest increasing subsequence, knapsack variants, matrix chain) - solved with Dynamic Programming (memoization/tabulation).
  2. Pathfinding, connectivity, or level-order processing in grids/graphs (number of islands, shortest path in maze, rotten oranges) - solved with Graph Traversal: BFS and DFS.
  3. Hierarchical data processing (tree diameter, in order traversal, BST validation, lowest common ancestor) - solved with Tree Traversals and Properties (pre/in/post-order, level-order, recursion/DFS on trees).
  4. Exhaustive search with pruning (permutations, subsets, N-Queens, sudoku solver, word search) - solved with Backtracking.
  5. Local optimal choices that work globally (jump game, task scheduler, fractional knapsack) - solved by Greedy Algorithms.
  6. Efficient "top-k" or priority processing (merge k sorted lists, kth largest element, task scheduler with cooldown) - solved with Heaps / Priority Queues.
  7. Efficient union of sets / cycle detection in graphs (redundant connection, number of provinces, Kruskal's MST) - solved with Union-Find (Disjoint Set Union) with path compression & union-by-rank.
  8. Searching in sorted/monotonic spaces (search in rotated sorted array, minimum in rotated array, binary search on answer for capacity problems) - solved by Binary Search (advanced variants).

Bonus:

Today I am going to talk about data structures that help repeatedly query aggregates (sum, min, max, etc.) over ranges of an array and perform updates at the same time.

Segment Trees and Fenwick Trees (also called Binary Indexed Trees or BIT) both solve this in O(log n) per operation, turning impossible brute-force solutions into efficient ones.

When to use them

Use these when the problem has:

  • Frequent range queries (sum/min/max/count of elements in [L, R])
  • Frequent point updates (change value at index i)
  • Array size n ≈ 105–106 and query count q ≈ 105–106

Classic scenarios:

  • Mutable range sum queries
  • Range minimum queries with updates
  • Counting inversions or coordinate compression helpers
  • Dynamic frequency queries

A segment tree is more flexible (supports range updates via lazy propagation, any associative operation like gcd/max).  

A Fenwick tree is simpler and lighter on memory, ideal for when you only need prefix sums (and derive range sums via prefix[R] - prefix[L-1]).

Segment Tree - Range sum query (mutable)

A Segment Tree is a full binary tree where:

  • Each node represents a range (segment) of the array
  • Leaf nodes hold individual array elements
  • Internal nodes hold the aggregate (sum/min/max) of their children
  • Built in O(n) space (typically 4n array size) and O(n) time

Operations:

  • Build: O(n)
  • Update (point): O(log n)
  • Query (range): O(log n)

Classic problem: Range Sum Query - Mutable

Problem statement: Given an integer array nums, handle multiple queries of the following types:

  • Update the value of an element in nums.
  • Calculate the sum of the elements of nums between indices left and right inclusive, where left <= right.
int[] nums = [1, 3, 5];
var st = new SegmentTree(nums);
Console.WriteLine(st.Query(0, 2)); // 9
st.Update(1, 2);
Console.WriteLine(st.Query(0, 2)); // 8

public class SegmentTree
{
    private int[] tree;
    private int n;

    public SegmentTree(int[] nums)
    {
        n = nums.Length;
        tree = new int[4 * n];
        Build(1, 0, n - 1, nums);
    }

    private void Build(int node, int start, int end, int[] nums)
    {
        if (start == end)
        {
            tree[node] = nums[start];
            return;
        }
        var mid = start + (end - start) / 2;
        Build(2 * node, start, mid, nums);
        Build(2 * node + 1, mid + 1, end, nums);
        tree[node] = tree[2 * node] + tree[2 * node + 1];
    }

    public void Update(int index, int val)
    {
        UpdateHelper(1, 0, n - 1, index, val);
    }

    private void UpdateHelper(int node, int start, int end, int idx, int val)
    {
        if (start == end)
        {
            tree[node] = val;
            return;
        }
        var mid = start + (end - start) / 2;
        if (idx <= mid)
            UpdateHelper(2 * node, start, mid, idx, val);
        else
            UpdateHelper(2 * node + 1, mid + 1, end, idx, val);

        tree[node] = tree[2 * node] + tree[2 * node + 1];
    }

    public int Query(int left, int right)
    {
        return QueryHelper(1, 0, n - 1, left, right);
    }

    private int QueryHelper(int node, int start, int end, int l, int r)
    {
        if (r < start || end < l) return 0;          // outside
        if (l <= start && end <= r) return tree[node]; // fully inside

        var mid = start + (end - start) / 2;
        var leftSum = QueryHelper(2 * node, start, mid, l, r);
        var rightSum = QueryHelper(2 * node + 1, mid + 1, end, l, r);
        return leftSum + rightSum;
    }
}

Complexity:

  • Build: O(n)
  • Update & Query: O(log n)
  • Space: O(4n) ≈ O(n)

Fenwick Tree - Range sum query

A Fenwick Tree is an array-based structure that uses bit manipulation to simulate tree-like prefix computations. It only needs O(n) space and is easier to code for sum-based problems.

Key operations:

  • update(idx, delta) - add delta to position idx
  • prefixSum(idx) - sum from 1 to idx
    • Range sum [L,R] = prefix(R) - prefix(L-1)

Note: Fenwick Trees are 1-indexed in practice.

Here is the same usage as above, but using a Fenwick Tree:

int[] nums = [1, 3, 5];
var ft = new FenwickTree(nums);
Console.WriteLine(ft.Query(0, 2)); // 9
ft.Update(1, 2); //1-based
Console.WriteLine(ft.Query(0, 2)); // 8

public class FenwickTree
{
    private int[] bit;
    private int[] values; // store original values for set-style updates
    private int n;

    public FenwickTree(int[] nums)
    {
        n = nums.Length;
        values = new int[n];
        bit = new int[n + 2]; // 1-based + extra
        for (var i = 0; i < n; i++)
        {
            values[i] = nums[i];
            Add(i + 1, nums[i]);
        }
    }

    private void Add(int idx, int delta)
    {
        while (idx <= n)
        {
            bit[idx] += delta;
            idx += idx & -idx; // lowest set bit
        }
    }

    public void Update(int index, int val)
    {
        var delta = val - values[index]; // compute delta for set
        values[index] = val;
        Add(index + 1, delta);
    }

    private int PrefixSum(int idx)
    {
        var sum = 0;
        while (idx > 0)
        {
            sum += bit[idx];
            idx -= idx & -idx;
        }
        return sum;
    }

    public int Query(int left, int right)
    {
        return PrefixSum(right + 1) - PrefixSum(left);
    }
}

Complexity:

  • Update & Prefix Query: O(log n)
  • Range Query: O(log n)
  • Space: O(n)

Comparison

Space:

  • Segment:O(4n)
  • Fenwick: O(n)

Build time:

  • Segment:O(n)
  • Fenwick: O(n log n)

Update

  • Segment:O(log n)
  • Fenwick: O(log n)

Range Query

  • Segment:O(log n)
  • Fenwick: O(log n) (via two prefixes)

Flexibility

  • Segment:"High: min/max/sum/gcd, lazy range updates"
  • Fenwick: Mostly sums (or invertible ops)

Code length / ease

  • Segment:"Longer, recursive"
  • Fenwick: "Shorter, iterative, bit magic"

Best for

  • Segment:"General aggregates, lazy propagation"
  • Fenwick: Pure point update + range sum problems

Conclusion

Start with Fenwick if the problem is pure range sum + point updates (faster to code, less error-prone). Switch to Segment Tree if you need min/max, range updates, or non-invertible operations.

Edge cases: index 0/1 confusion, negative values/deltas, empty ranges.

For very tight memory, Fenwick wins.

Intro

  At the moment I am looking for a job, so in my research into coding test platforms, the problems that cannot be solved with just a little thinking and some loops are 80% covered by just 8 categories of problems:

  1. Optimization with overlapping subproblems (coin change, longest increasing subsequence, knapsack variants, matrix chain) - solved with Dynamic Programming (memoization/tabulation).
  2. Pathfinding, connectivity, or level-order processing in grids/graphs (number of islands, shortest path in maze, rotten oranges) - solved with Graph Traversal: BFS and DFS.
  3. Hierarchical data processing (tree diameter, in order traversal, BST validation, lowest common ancestor) - solved with Tree Traversals and Properties (pre/in/post-order, level-order, recursion/DFS on trees).
  4. Exhaustive search with pruning (permutations, subsets, N-Queens, sudoku solver, word search) - solved with Backtracking.
  5. Local optimal choices that work globally (jump game, task scheduler, fractional knapsack) - solved by Greedy Algorithms.
  6. Efficient "top-k" or priority processing (merge k sorted lists, kth largest element, task scheduler with cooldown) - solved with Heaps / Priority Queues.
  7. Efficient union of sets / cycle detection in graphs (redundant connection, number of provinces, Kruskal's MST) - solved with Union-Find (Disjoint Set Union) with path compression & union-by-rank.
  8. Searching in sorted/monotonic spaces (search in rotated sorted array, minimum in rotated array, binary search on answer for capacity problems) - solved by Binary Search (advanced variants).

Bonus:

Two classic algorithms solve dealing with lots of strings elegantly: the Trie (prefix tree) for multiple prefix-based lookups, and KMP (Knuth-Morris-Pratt) for fast single-pattern searching in text. Today I am going to cover them both.

The Trie - Find the index of first occurrence (Prefix tree)

In computer science, a trie, also known as a digital tree or prefix tree, is a specialized search tree data structure used to store and retrieve strings from a dictionary or set. Unlike a binary search tree, nodes in a trie do not store their associated key. Instead, each node's position within the trie determines its associated key, with the connections between nodes defined by individual characters rather than the entire key.

So if a trie was an actual tree, then each branch would have a letter stamped on it. To find a "cat" you go on the "c" branch, then follow on the "a" subbranch and then on the "t" subbranch of "a". The computer science cat will be lying on that very branch - not to be confused with the spherical cow, that's another animal.

When to use

  • Insert many words and frequently check if a word exists
  • Check if any word starts with a given prefix (autocomplete!)
  • Search for words with wildcards or collect all words with a common prefix

Typical problems: dictionary implementations, word search on boards, replace words in sentences.

The point of a try is that sharing prefixes saves space and makes prefix queries very fast.

All operations have O(L) complexity, where L = word length:

  • Insert
  • Search (exact word)
  • StartsWith (prefix exists)

Here is an implementation of a trie:

var trie = new Trie();
trie.Insert("apple");
Console.WriteLine(trie.Search("apple"));     // true
Console.WriteLine(trie.Search("app"));       // false
Console.WriteLine(trie.StartsWith("app"));   // true
trie.Insert("app");
Console.WriteLine(trie.Search("app"));       // true

public class TrieNode
{
    public Dictionary<char, TrieNode> Children { get; } = [];
    public bool IsEndOfWord { get; set; }
}

public class Trie
{
    private readonly TrieNode root = new();

    public Trie() { }

    public void Insert(string word)
    {
        var node = root;
        foreach (var c in word)
        {
            if (!node.Children.TryGetValue(c, out var child))
            {
                child = new TrieNode();
                node.Children[c] = child;
            }
            node = child;
        }
        node.IsEndOfWord = true;
    }

    public bool Search(string word)
    {
        var node = GetNode(word);
        return node != null && node.IsEndOfWord;
    }

    public bool StartsWith(string prefix)
    {
        return GetNode(prefix) != null;
    }

    private TrieNode GetNode(string s)
    {
        var node = root;
        foreach (var c in s)
        {
            if (!node.Children.TryGetValue(c, out node))
                return null;
        }
        return node;
    }
}

The trie stands as one of the most elegant data structures for associative retrieval over strings. Independently conceived in the late 1950s, it was first formally described by René de la Briandais in 1959 as a way to compress lexicographic dictionaries, but the term "trie" itself - deliberately extracted from the middle syllable of "retrieval" - was coined by Edward Fredkin in his influential 1960 paper "Trie Memory" published in Communications of the ACM. Fredkin presented it as an alternative to unordered lists, ordered lists, or simple pigeonhole hashing for fast prefix-based lookup, insertion, and membership testing in large sets of variable-length keys.

Mathematically, a trie can be viewed as a rooted, ordered tree that realizes a deterministic finite automaton (DFA) whose states correspond to prefixes of the stored strings. Each edge is labeled with a single symbol from a finite alphabet Σ (of size typically |Σ| = 26 for English lowercase, 256 for bytes, etc.), and the path from the root to any node spells a unique prefix. A special end-of-word flag (or terminal marker) distinguishes nodes that complete valid keys. The height of any path equals the length of its corresponding string, so the time complexity for insertion, exact search, and prefix search is strictly O(L), where L is the length of the key, independent of the total number of strings N stored in the structure (unlike balanced binary search trees, whose operations are O(log N + L)). This prefix-independent bound arises because the trie performs exactly one transition per character, with no backtracking or comparison of entire keys.

Space complexity, however, reveals a classic time–space tradeoff. In the worst case (no shared prefixes), a trie requires Θ(∑ L_i) nodes and up to Θ(|Σ| × number of nodes) pointers, which can be far larger than a simple list or hash table. Yet in practice, for natural-language vocabularies or DNA sequences with significant prefix overlap, the compression is dramatic: the number of nodes often grows sublinearly with N, approaching a value proportional to the total number of distinct characters across all strings. Variants such as compressed tries (or Patricia tries / radix trees) further mitigate space by merging chains of unary nodes, achieving tighter bounds in many applications. Modern analyses (e.g., of hybrid or burst tries) frequently model expected node count and access cost using probabilistic methods over random string sets, confirming the trie's asymptotic superiority for prefix-heavy workloads despite its memory footprint.

Knuth-Morris-Pratt - Find the index of first occurrence (strStr)

KMP avoids unnecessary backtracking by precomputing the Longest Proper Prefix which is also Suffix (LPS / pi array) for the pattern.

Core steps:

  • Build LPS array for the pattern (what is the longest prefix that is also a suffix at each position)
  • Use the LPS to skip characters when mismatch happens - never backtrack in the text

When to use

  • Find if/where a pattern appears in a long text (especially if you do it repeatedly)
  • Avoid the O(n*m) worst-case of naive string search
  • Typical problems: implement strStr() / find substring index, repeated string matching,

Yes, you in the back! "But Siderite, isn't Boyer-Moore (with Galil rule) much better than Knuth-Morris-Pratt? Why are we even talking about this?"

That is an excellent question. The answer is that KMP is easier to implement under pressure and comprehend in a teaching context. Here are more reasons for KMP:

  • guaranteed linear time O(n + m)
  • boils down to the concept of LPS / failure / prefix table, which is a single array computed in O(m) and used in a clean two-pointer sliding window
    • it teaches prefix/suffix overlap, failure transitions, and amortized analysis in a compact way.
  • classic problems like "Implement strStr()", repeated substring patterns, or finding the first occurrence often map cleanly to KMP.
  • KMP (1977) is taught in almost every undergraduate algorithms textbook (CLRS dedicates space to it), while Boyer-Moore (1977, but refined later) is often presented as an "advanced" or "practical optimization" follow-up.

And speaking of strStr, let's see an implementation:

int StrStr(string haystack, string needle)
{
    if (needle.Length == 0) return 0;
    if (haystack.Length < needle.Length) return -1;

    var lps = ComputeLPS(needle);

    var i = 0; // index in haystack
    var j = 0; // index in needle

    while (i < haystack.Length)
    {
        if (haystack[i] == needle[j])
        {
            i++;
            j++;
        }

        if (j == needle.Length)
            return i - j; // found at i - j

        else if (i < haystack.Length && haystack[i] != needle[j])
        {
            if (j != 0)
                j = lps[j - 1]; // smart skip
            else
                i++;
        }
    }
    return -1;
}

int[] ComputeLPS(string pattern)
{
    var lps = new int[pattern.Length];
    var len = 0; // length of previous longest prefix suffix
    var i = 1;

    while (i < pattern.Length)
    {
        if (pattern[i] == pattern[len])
        {
            len++;
            lps[i] = len;
            i++;
        }
        else
        {
            if (len != 0)
                len = lps[len - 1];
            else
            {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

var haystack = "This is a Knuth-Morris-Pratt algorithm implementation";
Console.WriteLine(StrStr(haystack, "implementation")); //39

Complexity:

  • Building LPS: O(m)
  • Searching: O(n)
  • Total: O(n + m)

KMP is useful for repeated searches on the same pattern (build LPS once), or very long texts with many partial matches. If the problem has multiple patterns, consider Aho-Corasick (Trie + KMP ideas combined), but that's more of a practical real life problem than an interview one, so who cares, right?

The LPS (which stands for Longest Prefix Suffix) is a list created just from the pattern string before any searching starts. For each position in the pattern, the list records how long the beginning part of the pattern matches the ending part ending at that position (using the longest such match that is not the whole string up to there). When the search process finds a mismatch between pattern and text, instead of starting over from the beginning of the pattern, the algorithm uses the LPS value to skip ahead and resume checking from a later spot in the pattern.

In the example above, the LPS is just an array of zeroes, all except for the second 'i' in 'implementation' where the value is 1. So when a character mismatches that 'i', you start from index 1 and length 1, because 'implementation' starts with an 'i'.

You may be interested to know that the IndexOf implementation in .NET is neither KMP or BM, instead it's an optimized ordinal or culture-aware search that is implemented in native code (inside the CLR and CoreCLR runtime). So if you want either of these for specific cases, you will have to implement them yourself anyway. Or use a NuGet...

Conclusion

If you're into algorithms, the ones on strings are beautiful! People have been thinking about these for almost a century and there are some really cool implementations and ideas. I can't even begin to cover such a vast field.

Intro

  At the moment I am looking for a job, so in my research into coding test platforms, the problems that cannot be solved with just a little thinking and some loops are 80% covered by just 8 categories of problems:

  1. Optimization with overlapping subproblems (coin change, longest increasing subsequence, knapsack variants, matrix chain) - solved with Dynamic Programming (memoization/tabulation).
  2. Pathfinding, connectivity, or level-order processing in grids/graphs (number of islands, shortest path in maze, rotten oranges) - solved with Graph Traversal: BFS and DFS.
  3. Hierarchical data processing (tree diameter, in order traversal, BST validation, lowest common ancestor) - solved with Tree Traversals and Properties (pre/in/post-order, level-order, recursion/DFS on trees).
  4. Exhaustive search with pruning (permutations, subsets, N-Queens, sudoku solver, word search) - solved with Backtracking.
  5. Local optimal choices that work globally (jump game, task scheduler, fractional knapsack) - solved by Greedy Algorithms.
  6. Efficient "top-k" or priority processing (merge k sorted lists, kth largest element, task scheduler with cooldown) - solved with Heaps / Priority Queues.
  7. Efficient union of sets / cycle detection in graphs (redundant connection, number of provinces, Kruskal's MST) - solved with Union-Find (Disjoint Set Union) with path compression & union-by-rank.
  8. Searching in sorted/monotonic spaces (search in rotated sorted array, minimum in rotated array, binary search on answer for capacity problems) - solved by Binary Search (advanced variants).

Bonus:

Today I will be covering Binary Search, used to efficiently search sorted arrays or otherwise monotonic spaces.

When to use Binary Search

You already know classic binary search on a sorted array. But the real power shows up when the array is not obviously sorted, or when there is no array at all - only a monotonic (always increasing or always decreasing) decision space.

Classic signs:

  • The array is sorted but rotated / shifted
  • You need to find the minimum / maximum in a rotated sorted array
  • You're searching for the boundary between two behaviors (first true / last false)
  • You want the minimal / maximal value that satisfies some condition
  • The answer lies in a large but monotonic range (0 to 109, days, capacity, speed, etc.)
  • Linear search would be too slow, but the property lets you discard half the search space every step

One-sentence rule: Whenever you can define a monotonic predicate "is it possible / good enough at value X?" and the answer changes only once (from false to true or viceversa), binary search on the answer range will usually give you O(log N) time instead of O(N).

Classic Binary Search Template

I know that C# already has a method called Array.BinarySearch , but the problems you're going to get usually have a little quirk that forces you to implement it manually, like the array is sorted, then rotated. But it's really easy.

Use this pattern - it avoids off-by-one errors and integer overflow:

int BinarySearchLeftMost(int[] arr, int target)
{
    int left = 0;
    // note: one past the end
    int right = arr.Length;           

    while (left < right)
    {
        // same as (left+right)/2, but avoiding overflows
        int mid = left + (right - left) / 2;

        if (arr[mid] < target)
            left = mid + 1;
        else
            right = mid;
    }

    return left;   // insertion point or first >= target
}

Just remember:

  • left < right loop
  • mid = left + (right - left)/2 prevents overflow
  • When condition is true, shrink right
  • When false, shrink left
  • At the end left is usually the boundary you want
  • You may choose to use a simpler search algorithm when the size of the search is small enough

Example – Search in Rotated Sorted Array

Problem statement: You are given a sorted array that has been rotated an unknown number of times. Find the index of target or return -1.

Example: nums = [4,5,6,7,0,1,2], target = 0, expected output: 4

Here is the solution:

int Search(int[] nums, int target)
{
    var left = 0;
    var right = nums.Length - 1;

    while (left <= right)
    {
        var mid = left + (right - left) / 2;

        if (nums[mid] == target) return mid;

        // Left half is sorted
        if (nums[left] <= nums[mid])
        {
            if (nums[left] <= target && target < nums[mid])
                right = mid - 1;
            else
                left = mid + 1;
        }
        // Right half is sorted
        else
        {
            if (nums[mid] < target && target <= nums[right])
                left = mid + 1;
            else
                right = mid - 1;
        }
    }

    return -1;
}

int[] nums = [4, 5, 6, 7, 0, 1, 2];
var target = 0;
Console.WriteLine(Search(nums, target)); //4

It's silly, really. You just have an extra if/then block to figure out which of the halves is the unrotated one. Other than that it's a classic binary search.

Complexity goes from O(n) (the naive linear scan) to O(log n) for the binary search.

Example - Capacity to ship packages within D days

The problem is called Binary Search on Answer (Capacity To Ship Packages Within D Days).

Problem statement: Given weights of packages and D days, find the minimal ship capacity needed to ship all packages in D days.

Solution:

int ShipWithinDays(int[] weights, int days)
{
    // at least the heaviest package
    var left = weights.Max();
    // at most everything in one day
    var right = weights.Sum();

    while (left < right)
    {
        var mid = left + (right - left) / 2;

        if (CanShip(weights, mid, days))
        {
            // try smaller capacity
            right = mid;
        }
        else
        {
            left = mid + 1;
        }
    }

    return left;
}

bool CanShip(int[] weights, int capacity, int days)
{
    var current = 0;
    var neededDays = 1;

    foreach (var w in weights)
    {
        var newCurrent = current + w;
        if (newCurrent > capacity)
        {
            neededDays++;
            current = w;
            if (neededDays > days) return false;
        }
        else
        {
            current = newCurrent;
        }
    }
    return true;
}
Console.WriteLine(ShipWithinDays([1, 3, 45, 6, 4, 32, 24, 5, 6, 32], 4)); //49

Step-by-step checklist to recognize monotonicity in the example above:

  • What are we actually searching for?
    • We are searching for the smallest possible ship capacity (let's call it C) such that it is still possible to ship all packages in ≤ days days.
  • Define the clear yes/no question (the predicate): Is it possible to ship all packages using capacity ≤ C within ≤ days days?
    • We call this predicate CanShip(C, weights, days)
    • It returns true or false
  • Ask the crucial monotonicity question: If CanShip(C) is true, what happens when we increase C to C+1, C+2, etc.?
    • Answer: If you could already ship everything with capacity C, then you can definitely ship everything with any larger capacity (C+1, C+10, C+1000, ...).
    • In other words: larger capacity can only make the problem easier or keep it equally easy - never harder.
    • Formally: If CanShip(C) == true, then  CanShip(C') == true for all C' > C
    • The opposite is also true: If CanShip(C) == false, then CanShip(C') == false for all C' < C
  • Conclusion from the above:
    • The predicate CanShip(C) is monotonic non-decreasing with respect to C.
    • There exists some threshold value C_min such that:
      • for all C < C_min, meaning CanShip(C) = false
      • for all C ≥ C_min, meaning CanShip(C) = true
    • This is the classic "staircase" / "boundary" shape that binary search loves.

Visual intuition

Capacity: 

          false  false  false   true   true   true   true

                       ↑

                 the minimal valid capacity we want

Whenever increasing the search variable (capacity, speed, height, number of bananas per hour, pages per day, etc.) can only help (never hurt) the feasibility, then the feasibility function is monotonic, so binary search applies.

Ask yourself these two questions:

  • "If I make the constraint looser (bigger capacity, more days, higher speed limit, etc.), does the answer become easier or stay the same?
  • "If I make the constraint stricter (smaller capacity, fewer days, lower speed, etc.), does the answer become harder or stay the same?

If both answers are yes the feasibility is monotonic, therefore binary search on the answer is applicable.

Counter example: "find a number in an unsorted array" - increasing the search range doesn't consistently help or hurt. One must use linear scan or hash set, not binary search.

So in short: you know Example 2 is monotonic because making the ship capacity larger can only help (never hurt) the ability to finish in D days and that consistent direction creates the perfect binary-search-friendly boundary.

Example - Consistent hashing

Advanced Application: Consistent Hashing. Binary search shines on any sorted structure, not just arrays. One of the most elegant real-world uses is consistent hashing, the algorithm that powers load balancers, distributed caches, and databases like Cassandra and DynamoDB.

Use it when you are distributing keys (users, requests, cache entries) across a changing set of servers. Traditional hashing (key % numServers) forces every key to be remapped whenever a server is added or removed. Consistent hashing limits the damage to roughly 1/N of the keys.

Imagine a clock (the "ring") with numbers from -∞ to +∞.  

  • Each server gets many "virtual nodes" placed on the ring (via hash(server + replica)).  
  • The virtual nodes are kept sorted.  
  • To find where a key goes: hash the key (binary search for the first virtual node clockwise - the next larger hash, or wrap to the beginning).  
  • When a server is added/removed, only the keys between its old and new neighbors move.

We implement the ring with a List<long> (kept sorted) and BinarySearch, exactly the technique covered in this post.

Here is the solution:

var chr = new ConsistentHashRing();

chr.AddServer("server1");
chr.AddServer("server2");
chr.AddServer("server3");

Console.WriteLine("Before removal:");
Console.WriteLine($"key1   -> {chr.GetServerForKey("key1")}");
Console.WriteLine($"user42 -> {chr.GetServerForKey("user42")}");
Console.WriteLine($"cacheX -> {chr.GetServerForKey("cacheX")}");

chr.RemoveServer("server2");   // only ~1/3 of keys will move

Console.WriteLine("\nAfter removing server2:");
Console.WriteLine($"key1   -> {chr.GetServerForKey("key1")}");
Console.WriteLine($"user42 -> {chr.GetServerForKey("user42")}");
Console.WriteLine($"cacheX -> {chr.GetServerForKey("cacheX")}");

public class ConsistentHashRing
{
    private readonly List<long> ring = [];
    private readonly Dictionary<long, string> hashToServer = [];
    private readonly Dictionary<string, List<long>> serverToHashes = [];
    private const int VirtualNodesPerServer = 100; // increase for better distribution

    private long Hash(string key)
    {
        return Math.Abs(key.GetHashCode());
    }

    public void AddServer(string server)
    {
        if (serverToHashes.ContainsKey(server)) return;

        var hashes = new List<long>(VirtualNodesPerServer);
        for (int i = 0; i < VirtualNodesPerServer; i++)
        {
            long hash = Hash(server + "#" + i);

            int idx = ring.BinarySearch(hash);
            if (idx < 0) idx = ~idx;

            ring.Insert(idx, hash);
            hashToServer[hash] = server;
            hashes.Add(hash);
        }
        serverToHashes[server] = hashes;
    }

    public void RemoveServer(string server)
    {
        if (!serverToHashes.TryGetValue(server, out var hashes)) return;

        foreach (var hash in hashes)
        {
            int idx = ring.BinarySearch(hash);
            if (idx >= 0)
            {
                ring.RemoveAt(idx);
                hashToServer.Remove(hash);
            }
        }
        serverToHashes.Remove(server);
    }

    public string GetServerForKey(string key)
    {
        if (ring.Count == 0) return null;

        long hash = Hash(key);

        int idx = ring.BinarySearch(hash);
        if (idx < 0) idx = ~idx;
        if (idx == ring.Count) idx = 0; // wrap around the ring

        return hashToServer[ring[idx]];
    }
}

GetServerForKey does exactly one BinarySearch on the sorted list of virtual node hashes.

  • If the key hash lands exactly on a node then use it.
  • Otherwise ~idx gives the insertion point, i.e. the next server clockwise.
  • The wrap-around (if idx == Count) makes the ring circular.

That's O(log (N * replicas)) lookup, blazing fast even with thousands of virtual nodes.

Complexity:

  • Lookup (GetServerForKey): O(log (N * replicas)) thanks to BinarySearch
  • Add/Remove server: O(replicas * log (N * replicas)) (insert/delete in the list)

In practice N is small (10–1000 servers) and add/remove is rare, so it’s perfect.

Real-world notes:

  • Cassandra, DynamoDB, Redis Cluster, and most CDNs use this exact pattern.
  • In production replace the simple Hash with MD5, MurmurHash3, or SHA-1.
  • Virtual nodes (the 100 replicas) make distribution even - without them some servers would get way more keys than others.

Conclusion

Advanced binary search is one of the most powerful patterns in coding interviews. Once you see a monotonic property or decision boundary, you can often turn a brute-force O(n) or worse solution into O(log n) or O(n log n) with very little code.

Intro

  At the moment I am looking for a job, so in my research into coding test platforms, the problems that cannot be solved with just a little thinking and some loops are 80% covered by just 8 categories of problems:

  1. Optimization with overlapping subproblems (coin change, longest increasing subsequence, knapsack variants, matrix chain) - solved with Dynamic Programming (memoization/tabulation).
  2. Pathfinding, connectivity, or level-order processing in grids/graphs (number of islands, shortest path in maze, rotten oranges) - solved with Graph Traversal: BFS and DFS.
  3. Hierarchical data processing (tree diameter, in order traversal, BST validation, lowest common ancestor) - solved with Tree Traversals and Properties (pre/in/post-order, level-order, recursion/DFS on trees).
  4. Exhaustive search with pruning (permutations, subsets, N-Queens, sudoku solver, word search) - solved with Backtracking.
  5. Local optimal choices that work globally (jump game, task scheduler, fractional knapsack) - solved by Greedy Algorithms.
  6. Efficient "top-k" or priority processing (merge k sorted lists, kth largest element, task scheduler with cooldown) - solved with Heaps / Priority Queues.
  7. Efficient union of sets / cycle detection in graphs (redundant connection, number of provinces, Kruskal's MST) - solved with Union-Find (Disjoint Set Union) with path compression & union-by-rank.
  8. Searching in sorted/monotonic spaces (search in rotated sorted array, minimum in rotated array, binary search on answer for capacity problems) - solved by Binary Search (advanced variants).

Bonus:

Today I cover Union-Find (Disjoint Set Union).

When to use Union-Find

Determine problems that can be solved with Union-Find by these signs:

  • You need to repeatedly merge groups (union) and ask "are these two items in the same group?" (find).
  • You're counting connected components in a graph (number of provinces, number of islands alternative).
  • You're detecting cycles in an undirected graph or finding the redundant edge.
  • You're building a Minimum Spanning Tree (Kruskal's algorithm).
  • The graph is given as edges or adjacency matrix and n ≤ 104 (Union-Find is blazingly fast here).

One-sentence rule: If you repeatedly merge sets and check connectivity, Union-Find with path compression + union-by-rank gives you practically O(1) per operation (inverse Ackermann function α(n) - it never exceeds 5 for any practical n).

The data structure (reusable template)

We are going to use a class called UnionFind for all of the examples. It looks like this:

public class UnionFind
{
    private int[] parent;
    private int[] rank;
    public int Components { get; private set; }

    public UnionFind(int n)
    {
        parent = Enumerable.Range(0, n).ToArray();
        rank = new int[n];
        Components = n;
    }

    public int Find(int x)
    {
        var parentOfX = parent[x];
        if (parentOfX != x)
        {
            // path compression
            parentOfX = Find(parentOfX);
            parent[x] = parentOfX;
        }
        return parentOfX;
    }

    public bool Union(int x, int y)
    {
        var rootX = Find(x);
        var rootY = Find(y);

        // already same set -> cycle!
        if (rootX == rootY) return false;

        // Union by rank
        switch (rank[rootX].CompareTo(rank[rootY]))
        {
            case 1:
                parent[rootY] = rootX;
                break;
            case -1:
                parent[rootX] = rootY;
                break;
            case 0:
                parent[rootY] = rootX;
                rank[rootX]++;
                break;
        }

        Components--;
        return true;
    }
}

Example - Number of provinces

Let's check out the problem called Number of Provinces.

Problem statement: There are n cities. Some are connected by roads. A province is a group of directly or indirectly connected cities. Return the total number of provinces.

The input is a n*n matrix containing 1 (connected) or 0 (not connected).

Here is the code:

int FindCircleNum(int[][] isConnected)
{
    var n = isConnected.Length;
    var uf = new UnionFind(n);

    for (var i = 0; i < n; i++)
    {
        // upper triangle only
        for (var j = i + 1; j < n; j++)
        {
            if (isConnected[i][j] == 1)
            {
                uf.Union(i, j);
            }
        }
    }

    return uf.Components;
}

var matrix = new int[][]
{
    [1,1,0],
    [1,1,0],
    [0,0,1]
};
Console.WriteLine(FindCircleNum(matrix)); // 2

A possible naive approach: Run DFS or BFS from every unvisited city and count how many times you start a new traversal.

  • Time: still O(n2) because you may visit every edge/cell.
  • Problems: lots of extra code, recursion depth can exceed 104 leading to stack overflows, slower constants because of repeated visits and visited-array management.

Union-Find approach: We walk the matrix once, merging groups on the fly. No recursion, almost no extra memory, and each merge/check is practically O(1).

Complexity: O(n2 α(n)) where α(n) is the inverse Ackermann function (effectively constant). In practice this is faster than DFS/BFS and uses less memory.

Theory - why Union-Find is really fast

Imagine you have a bunch of people and you keep merging friend groups. A super-naive version would just keep a list for each group - merging two lists takes forever and checking "are these two friends?" also takes forever.

Without optimizations, Union-Find can degenerate into a long chain (like a linked list). In the worst case every Find would walk all the way to the root - O(n) time - and your whole algorithm would become O(n2). That's what the naive approaches usually suffer from. Union-Find fixes this with two tricks that you learn once and then use forever:

  • Path compression (the "flattening" trick): Every time you call Find(x), you make every node you touched point straight to the root. The next time anyone asks about those nodes, the answer is just one step.
  • Union by rank (the "keep trees short" trick): Instead of randomly attaching one tree under another, we always attach the shorter tree under the taller one (using the rank array). This guarantees the tree height stays tiny (at most log n in the worst case).

Together these two techniques give an amortized time per operation of O(α(n)), where α(n) is the inverse Ackermann function.

Don't worry about the math: α(n) grows so slowly that for any number you will ever meet in programming (even bigger than the number of atoms in the universe), α(n) ≤ 5. In practice it feels like constant time. That's why Union-Find turns problems that feel O(n2) into something that runs in the blink of an eye.

Example - Redundant connection

This problem is called Redundant Connection.

Problem statement: Given a list of edges that form a tree plus exactly one extra edge, return the extra edge that creates a cycle (the last one in the input if multiple).

The input is an array of n * 2 representing the edges between nodes.

A possible naive approach: For every new edge, temporarily add it and run a full DFS/BFS to see if u and v are already connected.

  • Time: O(n) per edge meaning O(n2) total.
  • Problems: slow, lots of code, and you still have to clean up the graph after each test.

Union-Find approach: We process each edge in one pass. Every union/find is amortized O(α(n)). As soon as we try to union two nodes that already have the same root, we found the cycle - no extra traversal needed.

Complexity: O(n α(n)) ≈ O(n). Dramatically faster and cleaner than any graph-traversal alternative.

using Algorithms;

int[] FindRedundantConnection(int[][] edges)
{
    // n edges for n nodes (labeled 1 to n)
    var n = edges.Length;
    var uf = new UnionFind(n + 1);

    foreach (var edge in edges)
    {
        var (u, v) = (edge[0], edge[1]);
        if (!uf.Union(u, v))
        {
            // this edge created the cycle
            return edge;
        }
    }

    return []; // never reached per problem constraints
}

var edges = new int[][]
{
    [1,2], [1,3], [2,3]
};
var result = FindRedundantConnection(edges);
Console.WriteLine($"[{result[0]},{result[1]}]"); // [2,3]

Example - Minimum spanning tree (Kruskal)

Problem statement: you are given n cities a list of possible connections between them. Each connection has a cost. Return the minimum total cost to connect all cities into one single network (i.e. a Minimum Spanning Tree). If it is impossible to connect all cities, return -1.

This is exactly Kruskal’s algorithm, the one we already mentioned in the "When to use Union-Find" section.

Input:

  • int n - number of cities
  • int[][] connections - each row is [city1, city2, cost]

Here is the complete solution (re-using the exact UnionFind class from the top of this post):

using Algorithms;

int MinimumCost(int n, int[][] connections)
{
    // Sort edges by increasing cost (greedy choice)
    var sorted = connections.OrderBy(e => e[2]).ToArray();

    var uf = new UnionFind(n + 1); // cities are 1..n
    var totalCost = 0;
    var edgesUsed = 0;

    foreach (var edge in sorted)
    {
        var u = edge[0];
        var v = edge[1];
        var cost = edge[2];

        if (uf.Union(u, v))
        {
            totalCost += cost;
            edgesUsed++;
            if (edgesUsed == n - 1) break; // MST is complete
        }
    }

    // We only need n-1 edges for n cities. If we found them → connected!
    return edgesUsed == n - 1 ? totalCost : -1;
}

var connections = new int[][]
{
    [1, 2, 3],
    [1, 3, 5],
    [2, 3, 1]
};
Console.WriteLine(MinimumCost(3, connections)); // 4  (edges 2-3 cost 1 + 1-2 cost 3)

A possible naive approach is to build a full graph and run Prim’s algorithm (priority queue + visited set).

  • Time: O(E log V) with a binary heap.
  • Problems: more code, needs adjacency list + heap, and you still have to handle disconnected graphs manually.

The Union-Find (Kruskal) approach:

  • Sort all possible edges by cost (O(E log E)).
  • Greedily add the cheapest edge that does not create a cycle (just call Union — if it returns false, skip it).
  • Stop when we have added n-1 edges or when Components == 1.

No graph traversal, no heap, no recursion — just the tiny UnionFind template we already have.

Complexity:

  • Time: O(E log E α(n)) — the sorting dominates, union/find is practically O(1) per operation.
  • Space: O(n) for the UnionFind arrays.

In practice this is often faster and simpler than Prim’s for sparse graphs (exactly the case in most interview problems).

Comparison

  • Use Kruskal + Union-Find when the graph is given as an edge list (most common in interviews).
  • Use Prim + Priority Queue (see the Heaps/Priority Queues post) when you already have an adjacency list or the graph is dense.

Both give the correct Minimum Spanning Tree - Union-Find just wins on simplicity and speed for this pattern.

Conclusion

Union-Find (Disjoint Set Union) is the hidden champion of graph problems: tiny code, good speed, and it turns "connected components" or "cycle detection" into trivial work. Once you internalize this template with path compression and union-by-rank, you'll spot it instantly in interviews and real code.