Contest problems rated 800 to 1,000 that ask a small question about a long list or string. The move: keep only the state the question needs, a few variables or a small table.
This tent holds problems rated 800 to 1,000. Each gives a long list, string or number and asks something small about it. The questions are the top three values, the letters that repeat, the closest pair, the longest stripe on a loop and a merge of two rows. Then come the balanced stretches, the digit sum of a power and the number of divisors.
The statements are short and the answers are short. The limits are not: lists of 100,000 values, numbers up to 10^12, and a power with an exponent of 10,000. So the work is to keep exactly what the question needs.
| Problem | What it keeps |
|---|---|
| Sort three numbers | three variables, kept in order |
| Count the letters that repeat | a table of 26 counts |
| Closest pair of values | the list in sorted order, then neighbours |
| Balanced zeros and ones | the length of the current run and of the one before it |
| Sum of the digits of a power | the big number, in cells of nine digits |
| Count the divisors | a loop up to the square root |
A first idea is usually a comparison of everything with everything. A list of 100,000 values has 4,999,950,000 pairs, and a judge runs about 10^8 simple steps a second. So each problem asks for a smaller idea.
Take the top values. Keep them in variables, and let each new value find its place.
Exercise · Predict the output: Who holds the two top places?. This keeps the two highest values of a list. Equal values count separately. An empty place holds -1. What does it print?
first = -1
second = -1
for value in [4, 9, 9, 2]:
if value > first:
second = first
first = value
elif value > second:
second = value
print(first, second)Read the question and ask which facts about the part already read can change the answer. Keep those facts, and drop the rest.
For the top three, the facts are three values. For the repeated letters, they are 26 counts. For balanced stretches, they are the lengths of two runs. Each fact is updated when the next item arrives, so one pass is enough.
After reading k items, a few variables or a small table describe everything about those items that the answer can depend on.
Sorting is the other tool. When the answer lives between neighbours, as in the closest pair, one sort replaces a search over all pairs.
The bug in these problems is rarely the idea. It is a start value, or a border that no change of symbol closes. In the run lengths below, current counts the symbol at position 0 already, and previous is empty.
Count balanced stretches from run lengths: at each border between two runs, the shorter run gives the number of stretches.
Exercise · Find the bug: The run that starts empty. A stretch of results is balanced when its first half is all one symbol and its second half all the other. This counts them from the lengths of runs. Which line is wrong?
def count_flaps(checks):
flaps = 0
previous = 0
current = 0
for i in range(1, len(checks)):
if checks[i] == checks[i - 1]:
current += 1
else:
flaps += min(previous, current)
previous = current
current = 1
flaps += min(previous, current)
return flapsFrequency, palindromes and anagrams taught the table of counts, and Simple sorts taught how to order values. Counting operations taught you to size a loop before you write it. This tent uses all three, and it adds the edge of each shortcut.
The divisor count shows the pattern. A divisor and its partner come as a pair whose product is n, so trying sizes up to the square root finds every pair. For n = 10^12 that is 10^6 tries instead of 10^12. For n = 963,761,198,400 the loop makes 981,713 tries and finds 6,720 divisors.
The edge is the square root itself. For n = 36, the pair 6 and 6 is one divisor, so the count is 9, and a loop that adds 2 for every hit gives 10.
The same care applies elsewhere. Equal balances are separate accounts, equal pins can reach the same smallest gap, and 9^10000 has 9,543 digits, far above any 64-bit integer.
Trying divisors up to the square root, add 2 for each hit except when the divisor equals its partner; the square root counts once.
Exercise · Break it: The pair that is one number. This counts the divisors of n by trying sizes up to the square root. Each hit adds 2: the divisor and its partner. Find an input where it is wrong.
def page_sizes(n):
count = 0
size = 1
while size * size <= n:
if n % size == 0:
count += 2
size += 1
return countThe limits tell you which shortcut you need before you read the story.
| Limit | What it rules out | What fits |
|---|---|---|
| a list of 10^5 values | all pairs: 5 x 10^9 | one pass, or one sort |
| 26 possible letters | a search for each letter | a table of 26 counts |
| a number up to 10^12 | a loop over 1 to n | a loop up to 10^6 |
| a power with exponent 10^4 | a 64-bit integer | cells of digits |
The full treatment is in Fast I/O and stress testing. For a long string, read the line once and count in a table.
import sys
def main():
word = sys.stdin.readline().strip()
counts = [0] * 26
for ch in word:
counts[ord(ch) - ord("a")] += 1
print(sum(1 for c in counts if c >= 2))
main()import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String word = in.readLine().trim();
int[] counts = new int[26];
for (int i = 0; i < word.length(); i++) counts[word.charAt(i) - 'a']++;
int repeated = 0;
for (int c : counts) if (c >= 2) repeated++;
System.out.println(repeated);
}
}#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string word;
cin >> word;
int counts[26] = {0};
for (char ch : word) counts[ch - 'a']++;
int repeated = 0;
for (int c : counts) if (c >= 2) repeated++;
cout << repeated << "\n";
}const word = require("fs").readFileSync(0, "utf8").trim();
const counts = new Array(26).fill(0);
for (const ch of word) counts[ch.charCodeAt(0) - 97]++;
console.log(counts.filter((c) => c >= 2).length);Pairs of values are easy to get almost right. The slow version below tries every pair, and the fast one sorts and looks at neighbours. The fast version keeps only the first closest pair, which is a common slip.
import random
def fast_pairs(positions):
ordered = sorted(positions)
best = min(b - a for a, b in zip(ordered, ordered[1:]))
for a, b in zip(ordered, ordered[1:]):
if b - a == best:
return [[a, b]]
def slow_pairs(positions):
best = min(abs(a - b) for i, a in enumerate(positions) for b in positions[i + 1:])
found = []
for i, a in enumerate(positions):
for b in positions[i + 1:]:
if abs(a - b) == best:
found.append([min(a, b), max(a, b)])
return sorted(found)
for seed in range(1000):
rng = random.Random(seed)
positions = rng.sample(range(30), rng.randint(2, 8))
if fast_pairs(positions) != slow_pairs(positions):
print("different at seed", seed, positions)
break
else:
print("all 1000 inputs agree")The run prints different at seed 0 [12, 24, 13, 1, 8, 16, 15, 29]. The values 12, 13 and 15, 16 both have a gap of 1, and the fast version reports only one. Over the first 1,000 seeds, 270 inputs show the difference.
Problems rated 800 to 1,000 need one small idea and care at the edge. The idea here is a smaller state. The edge is a tie, a border at the end, a square root or a number too large for 64 bits. Spend about 15 minutes on each, and keep five for a stress test.
The first ones keep a small state: three variables, a table of 26 counts, a sorted order, a cut point on a loop and two pointers. The last ones need a little more: run lengths, a number in cells and the square root.
For each problem, write in one line what you keep after reading k items. If you cannot say it in one line, the state is too big.
Checkpoint · Simple arrays and strings
Q1/5 A list has 100,000 values and you need its three highest. What do you keep while you read it?
Answer: B
Only the three highest values can change the answer. Comparing all pairs would need 4,999,950,000 steps.
Q2/5 A caption holds only the letters a to z. How do you count the letters that appear at least twice?
Answer: B
There are only 26 possible letters, so a table is enough, and it does not depend on the order of the letters.
Q3/5 How many divisors does 36 have, and what does a loop that adds 2 for every hit up to the square root give?
Answer: B
The pair 6 and 6 is one divisor. A loop that adds 2 for every hit counts it twice and gives 10.
Q4/5 A run-length count starts with current = 0 for a string of length 2, "01". What is the result?
Answer: B
Position 0 already belongs to the first run, so the run has length 1. Starting at 0 makes every run one short.
Q5/5 A fast closest-pair solution reports only the first closest pair. Which input finds it?
Answer: B
The pairs 12 and 13, and 15 and 16, both have a gap of 1. The statement asks for every pair that reaches the smallest gap.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.