Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
This is a Codeforces problem, so you read input and print output yourself (no function to fill in).
There are t test cases. Each gives an array a of length n. Count the pairs of indices i < j such that
a[j] − a[i] = j − iPrint one count per test case.
Example: a = [3, 5, 1, 4, 6, 6] → 1. The only good pair is i = 3, j = 5 (0-based): a[5] − a[3] = 6 − 4 = 2 and 5 − 3 = 2. The dry run below finds it without ever checking pairs.
Start with brute force
Check every pair i < j: O(n²). With n up to 2·10⁵, that's about 2·10¹⁰ checks — far too slow for a 2-second limit.
Building the intuition
The condition looks like it ties i and j together. Do some algebra and move all the i terms to one side and all the j terms to the other:
a[j] − a[i] = j − i
a[j] − j = a[i] − iNow each position has a single number that only depends on itself: key[k] = a[k] − k. A pair is good exactly when both positions have the same key.
So the question becomes: how many pairs share a key? That's a counting problem, and a hash map of "key → how many times seen so far" answers it in one pass, just like Two Sum and Subarray Sum Equals K.
This "separate the variables" move is one of the most useful tricks in competitive programming. Whenever a condition involves
iandj, try to rewrite it asf(i) = g(j).
The optimal approach
For each test case:
count = {}(key → how many earlier positions had it),answer = 0.- For each position
k:key = a[k] − kanswer += count[key]— every earlier position with this key pairs withkcount[key] += 1
- Print
answer(as a 64-bit integer).
It doesn't matter whether you use 0- or 1-based indices, as long as you're consistent — shifting every key by 1 doesn't change which keys are equal.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import sys
from collections import defaultdict
def main():
data = sys.stdin.buffer.read().split()
t = int(data[0])
pos = 1
out = []
for _ in range(t):
n = int(data[pos]); pos += 1
count = defaultdict(int) # key -> how many earlier positions had it
answer = 0
for k in range(n):
key = int(data[pos + k]) - k # a[j] - j == a[i] - i
answer += count[key] # pair with every earlier equal key
count[key] += 1
pos += n
out.append(str(answer))
print("\n".join(out))
main()#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
// key = a[k] - k lies in [-n, n], so an array offset by n beats a hash map
vector<long long> count(2 * n + 2, 0);
long long answer = 0; // can reach ~2e10: needs 64 bits
for (int k = 1; k <= n; k++) {
int a;
cin >> a;
int key = a - k + n; // shift so the index is never negative
answer += count[key]; // pair with every earlier equal key
count[key]++;
}
cout << answer << '\n';
}
return 0;
}import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(System.in, 1 << 16));
StringBuilder out = new StringBuilder();
int t = nextInt(in);
while (t-- > 0) {
int n = nextInt(in);
// key = a[k] - k lies in [-n, n], so an array offset by n is enough
long[] count = new long[2 * n + 2];
long answer = 0; // can reach ~2e10: needs 64 bits
for (int k = 1; k <= n; k++) {
int key = nextInt(in) - k + n; // shift so the index is never negative
answer += count[key]; // pair with every earlier equal key
count[key]++;
}
out.append(answer).append('\n');
}
System.out.print(out);
}
// Fast integer reader: Scanner is too slow for 2*10^5 numbers
private static int nextInt(DataInputStream in) throws IOException {
int ret = 0, b = in.read();
while (b != '-' && (b < '0' || b > '9')) b = in.read();
boolean neg = b == '-';
if (neg) b = in.read();
while (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
b = in.read();
}
return neg ? -ret : ret;
}
}// Codeforces: choose "Node.js" as the language
const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
let pos = 0;
const t = data[pos++];
const out = [];
for (let test = 0; test < t; test++) {
const n = data[pos++];
const count = new Map(); // key -> how many earlier positions had it
let answer = 0; // max ~2e10 is still exact in a JS number (< 2^53)
for (let k = 0; k < n; k++) {
const key = data[pos + k] - k; // a[j] - j == a[i] - i
const seen = count.get(key) || 0;
answer += seen; // pair with every earlier equal key
count.set(key, seen + 1);
}
pos += n;
out.push(answer);
}
console.log(out.join("\n"));Dry run
a = [3, 5, 1, 4, 6, 6] (0-based indices)
| k | a[k] | key = a[k] − k | count before | add | answer |
|---|---|---|---|---|---|
| 0 | 3 | 3 | {} | 0 | 0 |
| 1 | 5 | 4 | {3:1} | 0 | 0 |
| 2 | 1 | −1 | {3:1, 4:1} | 0 | 0 |
| 3 | 4 | 1 | {…, −1:1} | 0 | 0 |
| 4 | 6 | 2 | {…, 1:1} | 0 | 0 |
| 5 | 6 | 1 | {…, 1:1, 2:1} | 1 | 1 |
The pair is i = 3, j = 5: a[5] − a[3] = 6 − 4 = 2 and 5 − 3 = 2. ✓ Answer: 1.
Complexity
- Time: O(n) per test case — one pass with O(1) average map operations. Because the sum of all
nis bounded, the whole input is O(total n). - Space: O(n) for the map.
Edge cases and traps
- Overflow. If all keys are equal, the answer is
n(n−1)/2 ≈ 2·10¹⁰, which doesn't fit in a 32-bitint. Uselong long(C++) orlong(Java). - Resetting between test cases. Create a fresh map for every test case.
- Slow input. Read input in bulk (
sys.stdin,BufferedReader,ios::sync_with_stdio(false)) — 2·10⁵ numbers is a lot for slow I/O. - Hash attacks in C++. On Codeforces,
unordered_mapcan be slowed down by crafted tests. Since keys here lie in a small range (a[k] − kis between −n and n), an array offset bynis the bullet-proof option.
Say it in the interview
"Checking all pairs is O(n²). I rewrite a[j] − a[i] = j − i as a[j] − j = a[i] − i, so every index has its own key and a good pair is just two indices with the same key. Walking once and adding the count of earlier equal keys gives O(n). The answer can reach about 2·10¹⁰, so I use 64-bit integers."
Follow-ups interviewers ask
- "What if the condition were a[j] + a[i] = j − i?" Rearrange:
a[i] + i = j − a[j]. Now you need pairs where one side's key matches the other's — counta[i] + ias you go and look upj − a[j]. - "Count pairs with a[j] − a[i] = k (a constant)?" That's Two Sum-style counting with
a[j] − kas the lookup.
Practise the same idea
This is Day 18 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free