惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
W
WeLiveSecurity
V
Vulnerabilities – Threatpost
P
Privacy & Cybersecurity Law Blog
Cisco Talos Blog
Cisco Talos Blog
Blog — PlanetScale
Blog — PlanetScale
博客园 - 叶小钗
爱范儿
爱范儿
C
CERT Recently Published Vulnerability Notes
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Know Your Adversary
Know Your Adversary
Latest news
Latest news
T
Tor Project blog
NISL@THU
NISL@THU
The Hacker News
The Hacker News
IT之家
IT之家
Last Week in AI
Last Week in AI
T
Tenable Blog
C
Cybersecurity and Infrastructure Security Agency CISA
阮一峰的网络日志
阮一峰的网络日志
小众软件
小众软件
D
Darknet – Hacking Tools, Hacker News & Cyber Security
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
T
The Exploit Database - CXSecurity.com
博客园 - 三生石上(FineUI控件)
Spread Privacy
Spread Privacy
S
Secure Thoughts
博客园 - 司徒正美
A
About on SuperTechFans
Attack and Defense Labs
Attack and Defense Labs
Microsoft Security Blog
Microsoft Security Blog
N
News and Events Feed by Topic
O
OpenAI News
V
V2EX
aimingoo的专栏
aimingoo的专栏
L
LangChain Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security Affairs
MyScale Blog
MyScale Blog
S
Schneier on Security
宝玉的分享
宝玉的分享
Hacker News - Newest:
Hacker News - Newest: "LLM"
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Read Constraints and Immediately Know the Algorithm: A Jedi's Guide
Timevolt · 2026-06-21 · via DEV Community

Timevolt

The Quest Begins (The "Why")

I still remember the first time I stared at a competitive‑programming statement and felt my brain short‑circuit. The problem talked about “arrays of length n where each element is at most 10⁹ and you need to count pairs whose sum is divisible by k”. I started scribbling brute‑force loops, then switched to sorting, then tried hash maps… and after twenty minutes I was still staring at a blank editor, wondering if I’d missed some hidden trick.

Sound familiar? You’re not alone. The real dragon we’re slaying isn’t the syntax or the language quirks—it’s the mental block that makes us treat every constraint as noise instead of a clue. Top coders don’t read a problem and then start coding; they read the constraints first, let them whisper the algorithm, and only then do they touch the keyboard.

My breakthrough came during a late‑night practice session after I’d been stuck on a seemingly innocent problem for hours. I was about to give up when I noticed something: the limits were tiny for one dimension and huge for another. That mismatch screamed “there’s a shortcut”. When I finally saw it, it felt like Neo dodging bullets in The Matrix—everything slowed down, and the solution slid into place.

The Revelation (The Insight)

Here’s the exact mental framework I now use, step by step. Think of it as a quick checklist you run through before you write a single line of code.

Constraint pattern What it usually means Typical algorithm
n ≤ 10⁵, values ≤ 10⁶ Input is large but values are small enough to index Counting sort / frequency array / prefix sums
n ≤ 10⁵, values ≤ 10⁹ Values are too big for direct indexing, but n is moderate Hash map (unordered_map / dict) for frequencies
n ≤ 2000 O(n²) is fine (≈4 M ops) Brute force with early break or DP
n ≤ 10⁵, k ≤ 10⁵ Modulo or remainder constraints appear Bucket by remainder, combine counts
n ≤ 10⁵, sum of n across test cases ≤ 10⁶ Overall work must be near‑linear Single pass, O(n) or O(n log n)
n ≤ 10⁵, queries ≤ 10⁵, static array Many range queries, no updates Prefix sums, sparse table, or segment tree
n ≤ 10⁵, queries with updates Need both point updates and range queries Fenwick tree (BIT) or segment tree
Graph, m ≤ 2·10⁵, n ≤ 2·10⁵ Sparse graph BFS/DFS, union‑find, Dijkstra with heap
Graph, m ≈ n² Dense graph Floyd‑Warshall or adjacency‑matrix DP
String length ≤ 10⁵, alphabet small Small alphabet enables counting/trie tricks Counting sort, trie, or automaton
String length ≤ 10⁵, alphabet large Need hashing or suffix structures Rolling hash, suffix array, Z‑function
Answer fits in 64‑bit, but intermediate may overflow Watch for overflow, use long long / bigint Use 128‑bit if language allows, else split

The key is pattern‑matching: each constraint tells you which data structure will keep the complexity in the sweet spot. If you see a small value range, think “frequency array”. If you see a large value range but a modest n, think “hash map”. If you see a modulo or a divisor, think “bucket by remainder”.

When I internalized this table, I stopped guessing. I started scanning the bullet points, ticking off the matching row, and the algorithm practically wrote itself.

Wielding the Power (Code & Examples)

Let’s walk through a real problem that tripped me up before I had this framework.

Problem statement (paraphrased)

Given an array a of length n (1 ≤ n ≤ 2·10⁵) and an integer k (1 ≤ k ≤·10⁵), count the number of pairs (i, j) with i < j such that (a[i] + a[j]) % k == 0.

Values of a[i] are up to 10⁹.

Before the insight – the struggle

My first instinct was to try a hash map of frequencies and then, for each element, look for its complement. That’s O(n) if we can find the complement quickly, but I kept second‑guessing myself: “Do I need to handle the case where the complement equals the element itself? What about double counting?” I ended up writing nested loops, then aborting because O(n²) would TLE.

// Attempt 1 – naive O(n²) (will TLE)
long long ans = 0;
for (int i = 0; i < n; ++i)
    for (int j = i + 1; j < n; ++j)
        if ((a[i] + a[j]) % k == 0) ++ans;

After the insight – the victory

Now I run the checklist:

  • n ≤ 2·10⁵ → large, need near‑linear.
  • k ≤ 10⁵ → modest, we can afford an array of size k.
  • Values are up to 10⁹ → too big for direct indexing, but we only need remainders modulo k.
  • The condition involves a sum modulo k → classic “remainder pairing”.

Aha! Build a frequency array of size k for a[i] % k. Then for each remainder r, its complement is (k - r) % k. Count pairs using the frequencies, taking care of the special cases r == 0 and, when k is even, r == k/2.

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, k;
    if(!(cin >> n >> k)) return 0;
    vector<int> a(n);
    for (int &x : a) cin >> x;

    vector<long long> cnt(k, 0);
    for (int x : a) cnt[x % k]++;

    long long ans = 0;
    // pairs where both remainders are 0
    ans += cnt[0] * (cnt[0] - 1) / 2;

    // if k is even, handle the middle remainder separately
    if (k % 2 == 0) {
        ans += cnt[k/2] * (cnt[k/2] - 1) / 2;
    }

    // pair r with k-r for 1 <= r < k/2 (or < (k+1)/2 when k odd)
    int limit = (k % 2 == 0) ? k/2 : (k/2)+1;
    for (int r = 1; r < limit; ++r) {
        ans += cnt[r] * cnt[k - r];
    }

    cout << ans << '\n';
    return 0;
}

Why this works:

  • We reduced the problem from O(n²) to O(n + k) by focusing only on remainders, which are bounded by k.
  • The frequency array is trivial to allocate because k ≤ 10⁵.
  • The special‑case handling prevents double‑counting and avoids the “self‑pair” pitfall.

Common traps to avoid

  1. Forgetting the r == 0 case – you’ll miss pairs where both numbers are individually divisible by k.
  2. Double‑counting when k is even – the remainder k/2 pairs with itself, not with a distinct counterpart.
  3. Using int for the answer – the number of pairs can be up to ~2·10¹⁰, which overflows a 32‑bit int. Use long long (or int64_t).

Why This New Power Matters

Armed with this constraint‑first mindset, you’ll stop feeling like you’re wandering in a maze every time you open a problem statement. Instead, you’ll:

  • Spot the optimal data structure in seconds – no more “let’s try a map, maybe a tree, maybe brute force”.
  • Write fewer bugs – because the algorithm follows directly from the limits, you’re less likely to overlook edge cases.
  • Enjoy the coding – the moment the constraints whisper the answer, it feels like unlocking a secret level in a game.

Imagine walking into a contest, glancing at the first two lines of each problem, and already knowing whether to reach for a Fenwick tree, a trie, or a simple frequency array. That’s the kind of confidence that turns a good programmer into a great one.

Your Turn – A Mini‑Quest

Here’s a tiny challenge to test your new intuition:

You’re given n (≤ 10⁵) integers each ≤ 10⁶. You need to answer q (≤ 10⁵) queries of the form “how many numbers in the interval [l, r] are prime?”.

Read the constraints, pick the technique, and write the solution. When you’ve got it, drop your approach in the comments—I’d love to see how the framework works for you!

Happy coding, and may your constraints always be your guide. 🚀