Damus

Recent Notes

codementor profile picture
Learn: Race condition

When two threads read and write the same data at once, the result depends on who gets there first. count++ looks like one step, but it is read, add, write: two threads can read the same old value and one update is lost.

```csharp
int count = 0;
Parallel.For(0, 100_000, _ => Interlocked.Increment(ref count));
Console.WriteLine(count);
```

It prints 100000 every time. With plain count++ it can print less. Fixes: Interlocked for simple counters, lock for more.

Read more: https://learn.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices

#tip · TIP-073
codementor profile picture
Learn: Costs worth knowing by heart

Read array[i]: O(1)
Search an unsorted array: O(n)
Sort: O(n log n)
HashSet or Dictionary lookup: O(1) on average
Search a sorted array with binary search: O(log n)

When you state a solution in an interview, say its Big-O with it.

#tip · TIP-005
codementor profile picture
Learn: Factory

A factory creates objects for you, so the caller asks for "a pdf exporter" without naming the class.

```csharp
Console.WriteLine(Create("pdf").Export());
static IExporter Create(string kind) => kind switch
{
"pdf" => new PdfExporter(),
"csv" => new CsvExporter(),
_ => throw new ArgumentException(kind),
};
interface IExporter { string Export(); }
class PdfExporter : IExporter { public string Export() => "PDF file"; }
class CsvExporter : IExporter { public string Export() => "CSV file"; }
```

It prints PDF file.
Use it when: which class to create depends on input or configuration, or creating it is complicated.

Read more: https://www.geeksforgeeks.org/system-design/factory-method-for-designing-pattern/

#tip · TIP-052
1
prism597 · 17h
🪂 АirdroР alᎬrᎢ: https://one.evmverse.cc/?ref=xmovga 🪂 ᎪirdroΡ ᏚeᎪᏚon iᏚ hᎬrΕ.
codementor profile picture
Learn: PriorityQueue for "smallest first"

.NET has PriorityQueue<TElement, TPriority>. Dequeue always returns the item with the lowest priority value.

```csharp
var pq = new PriorityQueue<string, int>();
pq.Enqueue("low", 5); pq.Enqueue("urgent", 1); pq.Enqueue("mid", 3);
Console.WriteLine(pq.Dequeue());
```

It prints urgent. Use it for "top k" problems, merging k sorted lists, and Dijkstra's shortest path.

#tip · TIP-011
codementor profile picture
Learn: Hashing

What: a hash function turns a key into a number that picks a bucket, so a lookup jumps straight to the right place.
Cost: insert, find and delete are O(1) on average; many collisions can slow them down.
Use it when: you look things up by key, count things, remove duplicates, or cache results.

```csharp
var counts = new Dictionary<string, int>();
foreach (var w in "to be or not to be".Split(' '))
counts[w] = counts.GetValueOrDefault(w) + 1;
Console.WriteLine(counts["be"]);
```

It prints 2. In C#: Dictionary<K, V> and HashSet<T>.

Read more: https://www.geeksforgeeks.org/dsa/hashing-data-structure/

#tip · TIP-024
codementor profile picture
Learn: Linear search

What: check the items one by one until you find the target.
Cost: O(n) in the worst case, O(1) extra memory.
Use it when: the data is not sorted, is small, or you search only once. Sorting first costs O(n log n), more than one linear search.

```csharp
int[] a = { 7, 3, 9, 1 };
Console.WriteLine(Array.IndexOf(a, 9));
Console.WriteLine(Array.IndexOf(a, 5));
```

It prints 2, then -1 (not found). Array.IndexOf and List<T>.Contains are linear searches.

Read more: https://www.geeksforgeeks.org/dsa/linear-search/

#tip · TIP-033
codementor profile picture
Learn: CAP, the short version

When the network between servers breaks, so they can't talk to each other (a partition), a distributed system must choose: answer with possibly old data (availability) or refuse until it is sure (consistency).

Without a partition you can have both. Interviewers want you to say which one your design picks, and why.

#tip · TIP-017
codementor profile picture
Learn: Test your code by hand

When your code is written, don't just say "done". Walk through it with a small example, line by line, and say the values out loud.

Then try the edge cases: an empty input, one item, and all items the same. Most bugs show up in these three.

#tip · TIP-004
codementor profile picture
Learn: Sharding splits data by a key

When one database is too big or too busy, split the data across several databases (shards), for example by user ID.

The risk is a hot shard: if one key gets most of the traffic, one shard does most of the work. Choose a key that spreads load evenly.

#tip · TIP-016
codementor profile picture
Learn: Task vs Thread

A Thread is an operating system thread: expensive to create, and it holds memory the whole time.
A Task is a promise of a result. CPU work started with Task.Run runs on a shared pool of threads. A task waiting for I/O (a web call, a database) holds no thread at all while it waits.

In modern C#, use Task and async/await; create a Thread yourself only for rare long-running, dedicated work.

Read more: https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-based-asynchronous-programming

#tip · TIP-045
codementor profile picture
Learn: SemaphoreSlim, the async-friendly lock

A semaphore lets up to N callers in at a time. With N = 1 it is a lock that works with await.

```csharp
var gate = new SemaphoreSlim(1, 1); // one caller at a time, and it works with await
await gate.WaitAsync();
try { await Task.Delay(10); Console.WriteLine("saved"); }
finally { gate.Release(); }
```

It prints saved. Always release in finally.
Use it to protect code that awaits, or to limit concurrency: new SemaphoreSlim(5, 5) for "at most 5 downloads" (give both numbers, or an extra Release raises the limit). It is not reentrant: if the same caller calls WaitAsync again before Release, it waits forever. WaitAsync can also take a CancellationToken.

Read more: https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives

#tip · TIP-077
codementor profile picture
Learn: OAuth 2.0 vs OpenID Connect

OAuth 2.0 is about access: it lets an app call an API for the user, with an access token.
OpenID Connect (OIDC) adds login on top: an ID token that says who the user is.
The usual flow for web and mobile apps is the authorization code flow with PKCE: the user logs in at the identity provider, the app gets a code, and swaps it for tokens.
Short version: access token → for the API; ID token → for the app, to know who logged in.

Read more: https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols-oidc

#tip · TIP-093