Skip to main content

Posts

Search

Search Search Any Topic from Any Website Search
Recent posts

Bit Flipping to Equilibrium

Bit Flipping and Equilibrium Theory In digital systems, we often want to bring a binary bit array to a specific equilibrium (e.g., all 1s or all 0s) using minimum operations . If we can flip exactly k bits at a time: Count the number of wrong bits: w . The minimum number of operations required = ceil(w / k) . If w % k ≠ 0 , the last operation may include already-correct bits. Flipping bits in a sliding window approach may require more steps, but choosing any k wrong bits at each step ensures the fewest operations. Example 1 Initial bits: [0, 1, 1, 0] Target equilibrium: all 1s → [1, 1, 1, 1] k = 2 (flip 2 bits at a time) Step 1: Count wrong bits Wrong bits = positions 0 and 3 → total w = 2 Minimum operations = ceil(w / k) = 1  Step 2: Flip 2 wrong bits Operation Bits Before Bits Flipped Bits After 1 [0, 1, 1, 0] [0, 3] [1, 1, 1, 1]  Example 2: Sliding Window Bits: [0, 1, 0, 0, 1] Target: all 1s → [1, 1...

How Load Balancer Decides Traffic Distribution

How a Load Balancer Decides Which Server Handles Traffic A load balancer decides which server should handle a request based on a traffic distribution algorithm. Its goal is to distribute traffic efficiently, prevent overload, and improve availability. 1. Basic Process A client sends a request to a website/app. The request first reaches the load balancer (not directly the servers). The load balancer selects one backend server using a predefined method. The request is forwarded to that server. The server responds back through the load balancer to the client. 2. Common Load Balancing Algorithms Round Robin Requests are distributed sequentially. Request 1 → Server A Request 2 → Server B Request 3 → Server C Request 4 → Server A (repeat) Pros: Simple Cons: Doesn’t consider serve...

B-Tree: Definition and Python Example

B-Tree: Definition and Python Example What is a B-Tree? A B-Tree is a self-balancing tree data structure that maintains sorted data and allows search, sequential access, insertions, and deletions in logarithmic time . Each node can have multiple keys . Designed for disk-based storage for efficiency. Commonly used in database indexes . Formal definition: A B-Tree of order m is a tree where each node contains at most m-1 keys, has at most m children, all leaves are at the same depth, and keys within a node are sorted. Why B-Trees Are Used in Databases Efficient for range queries ( > , < , BETWEEN ) Efficient for exact lookups ( = ) Can store many keys per node, reducing disk I/O Supports fast insertion and deletion while staying balanced Practical Python Example We can use the BTre...

From Slow Search to Fast Search Using Indexes

From Slow Search to Fast Search Using Indexes Understanding how indexes improve database performance and why B-Tree indexes are the default in relational databases. The Problem Take this example: The database contains millions of rows. Searching for “Ana” takes a long time. Current Implementation The database checks every single row until it finds Ana. This is called a full table scan . It’s like reading an entire book just to find one word. From Slow Search to Fast Search There’s a better way: use an index . An index works like the index of a book — it allows you to jump directly to the correct page instead of scanning everything. Create an Index CREATE INDEX idx_email ON users(email); Now, when we search for Ana, the database jumps directly to her row instead of scanning the entire table. Search Query SELECT * FROM users WHERE ema...

Handling 1 Million Fake API Requests

What to Do If Your API Suddenly Receives 1 Million Fake Requests If your API suddenly receives 1 million fake requests , your server slows down and logs flood. This is usually a DDoS attack or bot flood. 1. Put Protection in Front of Your Server (Most Important) Use a CDN + Web Application Firewall (WAF) such as: Cloudflare AWS (Shield + WAF) Fastly These services: Block bot traffic before it hits your server Rate-limit abusive IPs Detect DDoS patterns automatically Filter suspicious countries or networks 2. Enable Rate Limiting Node / Express Example const rateLimit = require('express-rate-limit'); app.use(rateLimit({ windowMs: 60 * 1000, max: 100 })); NGINX Example limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s; server { location /api/ { limit_req zone...

How to Reduce 20 Database Queries to One

How to Reduce 20 Database Queries to One If your homepage is triggering 20 separate database queries , that’s usually a classic N+1 query problem or inefficient data loading pattern. The goal is to reduce those queries by batching, eager loading, or restructuring how data is fetched. 1. Fix the N+1 Problem (Most Common Cause) Problem Example SELECT * FROM posts; Then for each post: SELECT * FROM users WHERE id = ?; If you have 20 posts → 1 + 20 = 21 queries. Solution: Use JOIN (Single Query) SELECT posts.*, users.name FROM posts JOIN users ON posts.user_id = users.id; 2. Use Eager Loading for Related Data Laravel Post::with('user')->get(); Django Post.objects.select_related('user') Rails Post.includes(:user) 3. Use Subqueries or Aggregates Instead of Separate Queries Instead of multiple COUNT queries: SELECT post...

DC Component of a Periodic Signal

DC Component (Zero-Frequency) – Complete Hand Calculation Guide The DC component (zero-frequency component) represents the average value or total area of a signal, depending on the transform used. 1. DC Component of a Periodic Signal The DC component of a periodic signal is its average value over one full period . Definition For a periodic signal x(t) with period T : DC component = (1/T) ∫₀แต€ x(t) dt Mean value Average value Zero-frequency component (in Fourier analysis) Continuous-Time X_DC = (1/T) ∫_{t₀}^{t₀ + T} x(t) dt You can integrate over any full period. Discrete-Time X_DC = (1/N) ฮฃ x[n], n = 0 to N-1 2. Examples (Periodic Signals) Example 1: Sine Wave x(t) = A sin(ฯ‰t) X_DC = 0 A pure sine (or cosine) has zero DC component. Example 2: Offset Sine Wave x(t) = A sin(ฯ‰t) + 3 X_DC = 3 The DC component e...

Python Code to Build Tree and Get Paths

Python Code to Build Tree and Get Paths Build Binary Tree and Get Root-to-Leaf Paths class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def build_tree(arr): if not arr: return None nodes = [TreeNode(v) for v in arr] for i in range(len(arr)): left = 2*i + 1 right = 2*i + 2 if left < len(arr): nodes[i].left = nodes[left] if right < len(arr): nodes[i].right = nodes[right] return nodes[0] def root_to_leaf_paths(root): paths = [] def dfs(node, path): if not node: return path.append(node.val) if not node.left and not node.right: paths.append(list(path)) else: dfs(node.left, path) dfs(node.right, path) path.p...

People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *