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

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
爱范儿
爱范儿
H
Help Net Security
V
Visual Studio Blog
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
MyScale Blog
MyScale Blog
The Cloudflare Blog
Martin Fowler
Martin Fowler
D
Docker
腾讯CDC
F
Fortinet All Blogs
雷峰网
雷峰网
GbyAI
GbyAI
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
博客园 - 叶小钗

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
How to Read Constraints and Immediately Know the Algorith...
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. 🚀