Search
30 results for “dfs”
Search results
Graph Traversal: BFS & DFS
Why breadth-first search's queue explores every neighbor before any of their children, guaranteeing the shortest path in an unweighted graph, while depth-first search's stack (or recursion) does the opposite and can't make that guarantee at all.
What is the defining structural difference between BFS and DFS, and what data structure does each rely on?
Breadth-first search considers every neighbor of a vertex before considering any of those neighbors' own outgoing edges, per NIST's definition, extremes are searched last, which is implemented with a queue: vertices are processed in the order they were discovered, level by level outward from the start. Depth-first search does the opposite, it considers a vertex's outgoing edges (children) before any of the vertex's siblings, plunging as deep as possible along one path before backtracking, and NIST notes it's "easily implemented with recursion," which uses the call stack implicitly as its ordering structure (or an explicit stack in an iterative version).
Why does BFS guarantee the shortest path in an unweighted graph, while DFS gives no such guarantee at all?
Because BFS processes vertices in strict order of distance from the start (via its queue, level by level), the first time it reaches any given vertex is necessarily via a shortest path to it, there's no way to discover a vertex at distance k before every vertex at distance k-1 has already been discovered. DFS has no such ordering property, it commits to going as deep as possible down one path before backtracking, so it can easily reach a target vertex via a long, winding path long before it would have found a much shorter one, there's nothing in DFS's structure that favors shorter paths over longer ones at all.
For the same graph, why might you choose DFS over BFS even though BFS finds shortest paths and DFS doesn't?
Shortest-path guarantees aren't always the goal, DFS is a natural fit for exhaustively exploring all possibilities along one path before trying another (backtracking problems, detecting cycles, topological sorting, finding connected components), where the actual requirement is "visit everything reachable" or "explore this branch fully before trying the next," not "find the closest thing first." DFS via recursion is also often simpler to implement for these problems, at the cost of consuming call-stack depth proportional to how deep the graph goes, which matters for very deep or very large graphs where an iterative approach (or BFS) avoids the recursion-depth risk entirely.
Why does using a monotonically increasing field (a sequential ID, a timestamp) as a shard key concentrate all new writes onto one shard, even with range-based sharding across many shards?
With range-based sharding, chunks are assigned contiguous ranges of shard-key values, and a monotonically increasing key means every new document's value is higher than every previously inserted one, so all new inserts land in whatever chunk currently owns the highest range, which lives on one specific shard. Every other shard, holding older, lower-valued ranges, receives none of the new write traffic at all, the exact "hot shard" problem, all insert load concentrated on a single shard regardless of how many total shards the cluster has.
What does hashed sharding trade away in exchange for fixing the monotonic-key hot-shard problem?
Hashed sharding computes a hash of the shard key value and assigns chunks by hash range instead of by the raw value, which scatters even monotonically increasing keys roughly evenly across shards, since consecutive input values hash to essentially unrelated output values. The trade-off is range-query locality: a query filtering a range of the original shard key values (like "the last 24 hours" on a timestamp key) can no longer be routed to one contiguous set of shards, because the corresponding hashed values are scattered unpredictably across the whole cluster, turning what would have been a single-shard query under range sharding into a broadcast query touching every shard.
Why does explicitly telling a model it's allowed to say "I don't know" measurably reduce hallucination, and what's a second, complementary technique for the same problem?
Without that explicit permission, a model under an implicit expectation to always produce a confident, complete answer will sometimes fill a real information gap with a plausible-sounding but fabricated one; stating outright that uncertainty is an acceptable answer removes that pressure and lets the model surface "I don't have enough information" instead of guessing. A complementary technique for long documents is asking the model to first extract direct, word-for-word quotes relevant to the task before generating any analysis, grounding its response in verifiable text it actually has in front of it, and then citing which quote supports each claim, rather than generating an answer freely and hoping it stayed faithful to the source.
Why does wrapping several statements in `BEGIN`/`COMMIT` matter, even for a multi-step operation that's logically one action?
Without an explicit transaction, PostgreSQL commits each statement independently the moment it succeeds; if a multi-step operation (debit one account, credit another) fails halfway through, the database is left in an inconsistent, partially-applied state with no way to undo the completed step. Wrapping the statements in `BEGIN`/`COMMIT` groups them so they can be committed or rolled back together, but that alone isn't automatic protection against every failure mode: PostgreSQL only aborts a transaction on its own when a statement raises an actual SQL error, an `UPDATE` that runs successfully but matches zero rows (a mistyped account id, for instance) is not an error at all, and would otherwise be committed as if the transfer had actually happened. Making the transaction genuinely safe means checking that each `UPDATE` affected exactly the one row expected and issuing an explicit `ROLLBACK` if either check fails, only issuing `COMMIT` once both checks pass.
Why does a chunk like "The company's revenue grew by 3% over the previous quarter" cause a retrieval failure even if it's embedded correctly?
That sentence is only meaningful with context the isolated chunk doesn't carry, which company, which quarter, information that likely lived in a heading or preceding paragraph that didn't survive the chunking boundary. Embedded on its own, the chunk's vector represents a generic, context-free statement about revenue growth, which means it won't be retrieved reliably for a query about "ACME Corp Q2 2023 earnings" even though it's exactly the right chunk, because nothing in its embedding actually encodes that it's about ACME Corp or Q2 2023 at all.
What does it mean for a secret to be "dynamic" or "short-lived," and why does that reduce risk compared to a long-lived static credential?
A dynamic secret is issued on demand, scoped to a single application instance or session, and expires automatically after a defined lease, a database credential minted when a service starts and revoked automatically when it stops, rather than a password typed in once and left valid indefinitely. If a short-lived secret leaks, its usefulness to an attacker is bounded by its remaining lease time, often minutes, instead of remaining valid until someone notices and manually rotates it. This is the same underlying idea as preferring IAM roles over long-lived access keys in a cloud provider, temporary credentials shrink the blast radius of a leak by construction, not by better hiding the secret.
What does it mean for a sorting algorithm to be "stable," and why does that matter for sorting by multiple keys in separate passes?
A stable sort guarantees that when two elements compare as equal under the current sort key, their original relative order is preserved rather than left unspecified. This matters directly for multi-key sorting done as a series of single-key sorts: sort by a secondary key first, then stably sort by the primary key, and elements sharing the same primary key retain their secondary-key order from the first pass, correctly producing a combined sort by (primary, secondary) without needing a single comparator that handles both keys at once. An unstable sort would silently scramble that secondary ordering among equal-primary-key elements.
Why does string escaping alone not fully prevent SQL injection?
Escaping tries to neutralize special characters (like quotes) so user input cannot break out of its intended string literal, but it is easy to get wrong, different databases and contexts (string literals, numeric contexts, identifiers, LIKE patterns) have different escaping rules, and a single missed case reopens the vulnerability. Parameterized queries avoid the problem entirely: user input is sent to the database separately from the query structure, so it can never be interpreted as SQL syntax regardless of its content.
What does "run to completion" mean for a single task or microtask, and why does it matter for reasoning about shared state?
Once a job (a task or a microtask) starts running, it executes entirely before any other job gets a chance to run, JavaScript cannot pause a running function partway through to let another callback interleave, the way a preemptively-scheduled thread in a language like C could be interrupted mid-function. This is what makes synchronous JavaScript code within a single function safe from data races on shared state without needing locks, whatever a function does to shared variables happens atomically from the perspective of any other queued job, even though the language is single-threaded and asynchronous.
A custom dropdown built entirely from styled divs passes a visual design review. What is likely still broken for a keyboard-only or screen-reader user, and why doesn't looking right catch it?
Without the correct ARIA roles/states (or, better, a native `<select>`), a div-based dropdown typically has no way to be reached or operated via keyboard alone (no built-in Tab/Enter/Arrow-key handling), and a screen reader has no semantic information telling it "this is a dropdown, it is currently closed, here are its options," so it may announce nothing meaningful at all. A purely visual review can't catch this because the div looks and behaves correctly with a mouse, the missing behavior only surfaces via keyboard navigation or assistive technology, which is exactly why accessibility has to be tested directly with a keyboard and a screen reader, not inferred from how a component looks.
DHCP Server Deployment on Hyper-V: From Scope Creation to Failover Configuration
Step-by-step deployment of a highly available DHCP service in a Hyper-V virtual environment
Docker Fundamentals
How images, containers, volumes, and networks fit together in Docker's runtime model, and the mental shift from "installing software" to "running a packaged image" that trips up newcomers.
What is the difference between S3, EBS, and EFS?
S3 is object storage accessed entirely through an HTTP(S) API, not mounted as a filesystem, built for unstructured data at virtually unlimited scale. EBS is block storage that attaches to exactly one EC2 instance at a time (Multi-Attach for io1/io2 is the narrow exception) and must live in the same Availability Zone as that instance, functioning as its persistent virtual hard disk. EFS is a fully managed NFS file system that is regional by default, replicated across multiple Availability Zones, and can be mounted concurrently by many instances at once. The choice comes down to access pattern: S3 for API-driven object access, EBS for a single instance's own low-latency block storage, EFS for a shared network file system across many instances.
What is the difference between durability and availability in S3, and why does it matter when picking a storage class?
Durability is the probability that a stored object is not lost over a year, and S3 Standard, Standard-IA, and every Glacier class are all designed for the same 99.999999999% (11 nines) durability. Availability is how often the object can actually be successfully retrieved on demand, and that number does vary by class, 99.99% for Standard down to 99.5% for One Zone-IA. It matters because a cheaper class is not automatically a less durable one, S3 One Zone-IA is exactly as durable as Standard-IA per object, but it is not resilient to the loss of its single Availability Zone at all, since it isn't replicated across multiple zones the way every multi-AZ class is.
What is the difference between a security group and a network ACL in a VPC?
A security group is stateful and attaches at the instance/ENI level: it only supports allow rules, and if inbound traffic is allowed, the corresponding response traffic is automatically allowed back out regardless of outbound rules. A network ACL is stateless and attaches at the subnet level: it supports both explicit allow and explicit deny rules, numbered and evaluated in order starting from the lowest number, and because it has no memory of prior traffic, allowing inbound traffic does not automatically allow the matching outbound response, that has to be permitted by its own rule. Security groups are the primary, fine-grained access control per resource; network ACLs are a coarser, optional second layer at the subnet boundary.
What is the difference between a public and a private subnet in a VPC?
The difference is entirely about the subnet's route table, not any property of the subnet itself: a public subnet has a route to an internet gateway for `0.0.0.0/0`, so resources with a public IP in it can reach and be reached from the internet directly. A private subnet has no such route, so its resources typically use a NAT gateway (in a public subnet) for outbound-only internet access, or no internet path at all. Both subnet types can otherwise have identical security group and NACL configuration; "public" and "private" describe reachability via routing, not a separate networking feature.
What does AKS (Azure Kubernetes Service) manage for you compared to running Kubernetes yourself on VMs?
AKS manages the Kubernetes control plane (API server, etcd, scheduler) at no direct cost for the control plane itself; you only pay for the worker nodes, which still run as VMs you have some visibility into but don't have to manually install or upgrade Kubernetes onto. Running Kubernetes yourself on plain VMs means standing up and maintaining the entire control plane, including its high availability and upgrade process, which is a substantial and ongoing operational burden. AKS trades some control-plane visibility for removing that burden, which is why it's the default choice for running Kubernetes on Azure unless there's a specific reason to self-manage.
What is the difference between Blob Storage, File Storage, and Disk Storage in Azure?
Blob Storage is object storage for unstructured data (images, backups, logs), accessed via HTTP/HTTPS APIs, not mounted as a filesystem. File Storage provides fully managed file shares accessible via the SMB or NFS protocol, usable as a network drive that multiple VMs can mount simultaneously. Disk Storage provides block-level storage attached to a single VM, functioning as its virtual hard disk. The choice depends on access pattern: Blob for API-driven unstructured data at scale, File for shared network-drive-style access across machines, Disk for a VM's own persistent local-feeling storage.
What is the difference between locally redundant storage (LRS), zone-redundant storage (ZRS), and geo-redundant storage (GRS)?
LRS replicates data three times within a single datacenter; it protects against hardware failure but not a datacenter-level outage. ZRS replicates synchronously across three availability zones within one region, protecting against a single datacenter failure while keeping data within the region. GRS replicates asynchronously to a second, geographically distant region on top of LRS in the primary region, protecting against a regional disaster at the cost of the secondary copy lagging slightly behind (eventual, not synchronous, consistency) and being unreadable by default unless read access is explicitly enabled (RA-GRS).
How do access tiers (Hot, Cool, Archive) affect Blob Storage, and what do they not affect?
Access tiers change the cost trade-off between storage price and access/retrieval price: Hot has the highest storage cost but cheapest, immediate access; Cool has lower storage cost but a higher per-access cost and is meant for infrequently accessed data; Archive has the lowest storage cost but data must be rehydrated (a process taking hours) before it can be read at all. What tiers do not affect is durability, the redundancy option (LRS/ZRS/GRS) determines durability independently of which access tier a blob is in, so a Cool or Archive blob is exactly as durable as a Hot one with the same redundancy setting.
Why does `set -euo pipefail` matter at the top of a script?
By default, Bash keeps executing after a command fails, treats referencing an unset variable as an empty string instead of an error, and reports a pipeline's exit status as only its last command's; all three hide real failures. `-e` exits on a non-zero status from most simple commands, but only in contexts where errexit actually applies; it does not trigger inside `if`/`while`/`until` conditions, for any but the last command in a pipeline (unless combined with `pipefail`), or for a non-final command in a `&&`/`||` list, whose status is checked by the operator itself rather than causing an exit. The final command in that list is not exempt, though: if it fails and the list isn't itself acting as an `if`/`while`/`until` condition or the left side of another `&&`/`||`, errexit still triggers. `-u` turns an unset-variable reference into an error, and `-o pipefail` makes a pipeline fail if any stage fails, not just the last one. Together they turn a script that silently continues past errors into one that fails loudly in the cases where errexit applies, which is almost always what you want for anything beyond a one-off interactive command, but it is not a blanket guarantee that catches every failure everywhere.
Why does an O(n log n) sort beat an O(n^2) sort for large inputs, even if the O(n^2) one is faster on small inputs?
Constant factors can make an O(n^2) algorithm faster for small n, Big O only describes the asymptotic trend, not the exact runtime. But growth rates diverge fast: at n = 1,000,000, n log n is about 20 million operations while n^2 is a trillion. Past a crossover point the asymptotically better algorithm always wins, which is why production sort implementations (like Timsort) still often special-case small arrays with a simpler O(n^2) sort under the hood.
What is the difference between time complexity and space complexity?
Time complexity describes how the number of operations grows with input size; space complexity describes how additional memory usage grows with input size. An algorithm can trade one for the other, memoization in dynamic programming typically turns exponential time into polynomial time by spending O(n) or more extra space to cache results.
What is the difference between a security group and a network ACL?
A security group is stateful and attached to individual resources (like an instance or load balancer), if you allow inbound traffic on a port, the corresponding outbound response is automatically allowed, and rules are evaluated as an allow-list only. A network ACL is stateless and attached to a subnet, evaluating both inbound and outbound rules independently for every packet, including explicit deny rules. Security groups are the primary, more commonly used tool for per-resource access control; network ACLs add a coarser, subnet-wide layer, often left at their permissive default and used mainly for defense-in-depth or to explicitly block something.
What is the cloud shared responsibility model, and why does it matter for security?
It's the explicit division of security obligations between the cloud provider and the customer, and where that line falls depends on the service model. The provider is always responsible for "security of the cloud", physical data centers, host infrastructure, and (for managed services) the underlying platform. The customer is always responsible for "security in the cloud", for IaaS, that includes OS patching, network configuration, and IAM; for PaaS, it narrows to application code, data, and access control; for SaaS, it's mostly just access control and data. Misunderstanding this line is one of the most common causes of real cloud security incidents, assuming the provider handles something they explicitly don't.
Why does a naive `hash(key) % N` scheme for distributing keys across N servers fall apart the moment a server is added or removed?
With plain modulo hashing, the server a key maps to depends directly on the current value of N, since almost every key's `hash(key) % N` result changes the instant N changes to N-1 or N+1, even though the underlying hash values themselves didn't change at all. That means adding or removing a single server can remap the overwhelming majority of keys to different servers simultaneously, which for a cache means a massive wave of cache misses, and for a sharded store means a massive, unnecessary data-migration event, triggered by a change to just one server out of many.