Use arrays, strings, maps, sets and sorting in Python, Java, C++ and JavaScript side by side.
Use it when a task counts, groups, looks up or orders values. Signal words: how often, unique, first seen, sort by.
Start pick the tool: a map to count or look up, a set to test membership, a sort to order.
Step read the list once, updating the map or set, or sort a copy with a key.
Stop compare the entries with a tie rule that does not depend on map order.
It does not change the class of the task. It makes the first pass cost n instead of n squared.
Cost: a map reads the list once, O(n). A sort costs O(n log n).
In this lesson you meet four tools in Python, Java, C++ and JavaScript: a list, a map, a set and a sort with a key. You write each solution with the same steps in all four languages. You also learn where the languages behave differently.
You work on the search box of an app. The team wants to know which word people type most often in a day. A day holds up to 100,000 typed words, in the order they were typed. The team writes its tools in four languages, and each must give the same answer.
Your team lead says: Show me the same solution in all four languages, and tell me where they behave differently.
So the task is to count the words, pick the most common one, and keep the four solutions in step.
A workshop has four toolboxes. Each holds a hammer, a saw and a ruler, but the handles and the labels differ. A carpenter who knows the jobs finds the tool in any box.
The jobs are the list, the map, the set and the sort. The boxes are the four languages.
Like four toolboxes: the same jobs, with different handles and labels in each language.
Count the words of one small day by hand. Then watch the same count in the widget.
Solve it by hand: Counting six typed words. The hand-solve sheet loads in your browser.
The words are rain, sun, rain, fog, sun, rain. Read them once and keep a count for each.
| Word read | Counts so far |
|---|---|
| rain | rain 1 |
| sun | rain 1, sun 1 |
| rain | rain 2, sun 1 |
| fog | rain 2, sun 1, fog 1 |
| sun | rain 2, sun 2, fog 1 |
| rain | rain 3, sun 2, fog 1 |
The most common word is rain, with 3.
Start with a correct version. For each word, count how often it appears by scanning the whole list, and keep the best.
def top_word_scan(words):
best_word = ""
best_count = 0
for a in range(len(words)): # each word
count = 0
for b in range(len(words)): # scan the whole list for it
if words[b] == words[a]: # one check
count += 1
if count > best_count or (count == best_count and words[a] < best_word):
best_word = words[a]
best_count = count
return best_wordIt is correct. It scans the list once for every word, so it makes n × n checks.
Now check the real size.
A day holds 100,000 typed words, and a machine does about 100,000,000 simple steps a second.
Here is the count:
The scan version is 100 times over a one-second limit.
Predict the cost
Q A method makes 10,000,000,000 checks at 100,000,000 steps a second. About how long does it take?
Answer: C
10,000,000,000 divided by 100,000,000 is 100 seconds.
The fix is a map: a table from a word to its count.
Can we count without scanning again? A map keeps one count for each word, so each word read costs one lookup and one update. Here are the four tools in the four languages.
| Tool | Python | Java | C++ | JavaScript |
|---|---|---|---|---|
| List | list |
int[], ArrayList |
vector |
Array |
| Map | dict |
HashMap |
unordered_map |
Map |
| Set | set |
HashSet |
unordered_set |
Set |
| Sort with a key | sorted(key=...) |
Arrays.sort(a, comparator) |
sort(begin, end, comparator) |
sort(comparator) |
Race: Steps of three ways to count words. The operation counter loads in your browser.
The race counts the steps of three methods at 1,000, 10,000, 100,000 and 1,000,000 words. At 100,000 the scan version makes 10,000,000,000 checks, the counting table 100,000 steps, and sorting the words 1,600,000 steps.
Exercise · Put it in order: Words that appear once. Arrange the lines into a function that counts the words typed exactly once in the day.
def count_singletons(words):
counts = {}
singles = 0
for word in words:
counts[word] = counts.get(word, 0) + 1
for count in counts.values():
if count == 1:
singles += 1
return singles
counts[word] = 1A map counts each word with one lookup and one update, so the list is read once.
Which word is the most common in tea, map, tea, map, bus? Two words appear twice, so the tie rule decides: take the alphabetically smaller word. The player asks you to predict.
Dry run: Predict each step: the tie rule. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | Value |
|---|---|
| Counts after reading | tea 2, map 2, bus 1 |
| Highest count | 2 |
| Words with count 2 | tea and map |
| Alphabetically smaller | map |
So the answer is map.
Each fact below comes from running the same small program in each language on one laptop: Python 3.11, OpenJDK 23, clang 21 and Node 22. Where a result is implementation-defined, the table says so.
| Behaviour | Python | Java | C++ | JavaScript |
|---|---|---|---|---|
-7 / 2 |
-7 // 2 is -4 |
-3 | -3 | Math.trunc(-7 / 2) is -3 |
-7 % 2 |
1 | -1 | -1 | -1 |
| Largest 32-bit int plus 1 | 2147483648 | wraps to -2147483648 | undefined behaviour | 2147483648 |
| Map order of banana, apple, cherry, date | insertion order | banana, date, apple, cherry (not promised) | unordered_map: date, apple, cherry, banana (not promised) | insertion order |
Sorting [10, 9, 1] by default |
[1, 9, 10] | [1, 9, 10] | [1, 9, 10] | [1, 10, 9], as text |
The map order row is the one to remember. Python's dict and JavaScript's Map keep the order keys were added. Java's HashMap and C++'s unordered_map promise nothing, and the order above came from one machine. A solution must never depend on it.
A sort is stable when items with equal keys keep their input order. On the same laptop, 200 pairs with seeded random first numbers from 0 to 9 were sorted by that number. Neighbouring ties out of input order: 92 with C++ std::sort, and 0 with std::stable_sort. A sort of only 4 pairs looked stable, which is why small tests do not reveal the problem.
Python's sorted, Java's sorts of objects and JavaScript's sort are documented as stable. C++ std::sort is not guaranteed to be stable on any machine. Use std::stable_sort when the order of ties matters, or add the tie-break to the comparator.
Exercise · Predict the output: Where do the equal-length words end up?. The words are sorted by length only, with a stable sort. What does this print?
words = ["plum", "fig", "kiwi", "apple", "pear", "ox"]
words.sort(key=len)
print(*words)In this course the judge calls your function, so you never read input yourself. Contest sites read standard input, and the choice of reader matters. These timings are for 1,000,000 numbers on one line, best of 3 runs on one laptop, including the start of the program. Your machine will differ.
| Language | Reader | Seconds |
|---|---|---|
| Python | sys.stdin.read().split() |
0.14 |
| Java | Scanner |
0.56 |
| Java | BufferedReader with StringTokenizer |
0.19 |
| C++ | cin |
1.44 |
| C++ | cin after ios::sync_with_stdio(false) |
1.48 |
| JavaScript | fs.readFileSync(0, "utf8").split(/\s+/) |
0.22 |
The C++ rows are the slowest here because this standard library (clang's, on this laptop) parses numbers slowly, and turning off the sync made no clear difference. Other libraries behave differently, so measure before you rely on a reader.
Here is the rule behind this lesson. Both templates use it.
Every language has the same four tools, so write the same steps in each and check where it differs.
The course writes every solution with the same steps and the same names. A reader can move from one language to another and find step 2 doing the same job.
Use it when a task counts, groups, looks up or orders values. Signal words: how often, unique, first seen, sort by.
Start: pick the tool: a map to count or look up, a set to test membership, a sort to order.
Step: read the list once, updating the map or set, or sort a copy with a key.
Stop: compare the entries with a tie rule that does not depend on map order.
It does not change the class of the task. It makes the first pass cost n instead of n squared.
Cost: a map reads the list once, O(n). A sort costs O(n log n).
Count each word in a map, then keep the word with the highest count. When two words have the same count, keep the alphabetically smaller word. The tie rule makes the answer the same in every language, whatever order the map uses.
def top_word(words):
# [1] A table from each word to how many times it appeared.
counts = {}
for word in words:
# [2] Count the word, starting from zero for a new one.
counts[word] = counts.get(word, 0) + 1
best_word = ""
best_count = 0
for word in counts:
# [3] Keep the higher count; on a tie keep the alphabetically smaller word.
if counts[word] > best_count or (counts[word] == best_count and word < best_word):
best_word = word
best_count = counts[word]
# [4] Return the top word, or the empty string for an empty list.
return best_wordpublic String topWord(String[] words) {
// [1] A table from each word to how many times it appeared.
java.util.HashMap<String, Integer> counts = new java.util.HashMap<>();
for (String word : words) {
// [2] Count the word, starting from zero for a new one.
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
String bestWord = "";
int bestCount = 0;
for (java.util.Map.Entry<String, Integer> entry : counts.entrySet()) {
String word = entry.getKey();
int count = entry.getValue();
// [3] Keep the higher count; on a tie keep the alphabetically smaller word.
if (count > bestCount || (count == bestCount && word.compareTo(bestWord) < 0)) {
bestWord = word;
bestCount = count;
}
}
// [4] Return the top word, or the empty string for an empty list.
return bestWord;
}#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
string topWord(const vector<string>& words) {
// [1] A table from each word to how many times it appeared.
unordered_map<string, int> counts;
for (const string& word : words) {
// [2] Count the word, starting from zero for a new one.
counts[word]++;
}
string bestWord = "";
int bestCount = 0;
for (const auto& entry : counts) {
const string& word = entry.first;
int count = entry.second;
// [3] Keep the higher count; on a tie keep the alphabetically smaller word.
if (count > bestCount || (count == bestCount && word < bestWord)) {
bestWord = word;
bestCount = count;
}
}
// [4] Return the top word, or the empty string for an empty list.
return bestWord;
}function topWord(words) {
// [1] A table from each word to how many times it appeared.
const counts = new Map();
for (const word of words) {
// [2] Count the word, starting from zero for a new one.
counts.set(word, (counts.get(word) ?? 0) + 1);
}
let bestWord = "";
let bestCount = 0;
for (const [word, count] of counts) {
// [3] Keep the higher count; on a tie keep the alphabetically smaller word.
if (count > bestCount || (count === bestCount && word < bestWord)) {
bestWord = word;
bestCount = count;
}
}
// [4] Return the top word, or the empty string for an empty list.
return bestWord;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The tie that picks the wrong word. The rule says: on a tie, keep the alphabetically smaller word. This function returns the larger one. Which line is wrong?
def top_word(words):
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
best_word = ""
best_count = 0
for word in counts:
if counts[word] > best_count or (counts[word] == best_count and word > best_word):
best_word = word
best_count = counts[word]
return best_wordSort a copy of the words by length, and by text when the lengths are equal. Each language spells the key differently.
def order_by_length_then_text(words):
# [1] Sort a copy, so the caller's list stays as it was.
ordered = list(words)
# [2] The key puts the length first, then the text.
ordered.sort(key=lambda word: (len(word), word))
# [3] Return the ordered words.
return orderedpublic String[] orderByLengthThenText(String[] words) {
// [1] Sort a copy, so the caller's list stays as it was.
String[] ordered = words.clone();
// [2] The key puts the length first, then the text.
java.util.Arrays.sort(ordered, (a, b) -> a.length() != b.length() ? Integer.compare(a.length(), b.length()) : a.compareTo(b));
// [3] Return the ordered words.
return ordered;
}#include <algorithm>
#include <string>
#include <vector>
using namespace std;
vector<string> orderByLengthThenText(const vector<string>& words) {
// [1] Sort a copy, so the caller's list stays as it was.
vector<string> ordered = words;
// [2] The key puts the length first, then the text.
sort(ordered.begin(), ordered.end(), [](const string& a, const string& b) {
if (a.size() != b.size()) {
return a.size() < b.size();
}
return a < b;
});
// [3] Return the ordered words.
return ordered;
}function orderByLengthThenText(words) {
// [1] Sort a copy, so the caller's list stays as it was.
const ordered = [...words];
// localeCompare is avoided below because its result depends on the locale.
// [2] The key puts the length first, then the text.
ordered.sort((a, b) => (a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0));
// [3] Return the ordered words.
return ordered;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the words this sort leaves in the wrong order. This function should order words by length, and by text when the lengths are equal. Find a list where it gives the wrong answer.
def order_by_length_then_text(words):
ordered = list(words)
ordered.sort(key=len)
return orderedSort a copy with a key: length first, then text. Python uses a pair, the others write a comparator.
Pick the tool in four steps.
A task counts how many different hostnames appear in a list of 50,000 requests. The job is membership, so the tool is a set. Insert each hostname, then return the size of the set.
Python uses len(set(hosts)), Java new HashSet<>(...) and size(), C++ an unordered_set and size(), and JavaScript new Set(hosts).size. One pass makes 50,000 steps. Comparing every pair would make about 1,249,975,000 checks.
Real data brings edge cases.
With words = [] the map is empty, and no word beats a count of 0. Template 1 returns the empty string. Decide this answer before you code.
With words = ["b", "a", "b", "a"] both words appear twice. The tie rule picks "a". A solution that keeps the first word it meets returns "b" in Python and JavaScript, and may return either in Java and C++.
With words = ["b", "a", "bb", "ab", "a"] Template 2 gives ["a", "a", "b", "ab", "bb"]. Length decides first, and text decides among equal lengths. Equal words are identical, so their order cannot show.
With 100,000 copies of "go", the map holds one entry and the count reaches 100,000. The answer is "go", and the count fits a 32-bit integer.
This version sorts numbers with list.sort() and no comparator.
Counterexample: in JavaScript [10, 9, 1].sort() gives [1, 10, 9], because numbers are compared as text. Python, Java and C++ give [1, 9, 10]. Pass (a, b) => a - b.
This version returns the first word it meets with the highest count, and relies on the map's order for ties.
Counterexample: on the words banana, apple, cherry, date, Java's HashMap listed banana, date, apple, cherry and C++'s unordered_map listed date, apple, cherry, banana on one laptop. Python and JavaScript listed them in input order. The same tie gives different answers.
Map order differs: Java and C++ listed the same four keys in different orders, so a tie can go either way.
This version builds a 3 by 3 grid with grid = [[0] * 3] * 3.
Counterexample: after grid[0][0] = 1, the grid is [[1, 0, 0], [1, 0, 0], [1, 0, 0]], because all three rows are one list. Build it with [[0] * 3 for _ in range(3)], which gives [[1, 0, 0], [0, 0, 0], [0, 0, 0]].
This version sorts C++ records by one key and expects equal keys to stay in input order.
Counterexample: take 200 pairs with seeded random first numbers from 0 to 9. Sorted by that number with std::sort, they gave 92 neighbouring ties out of input order on one laptop. std::stable_sort gave 0. Use stable_sort or add the tie-break to the comparator.
This Java version sorts an Integer[] with the comparator (a, b) -> a - b.
Counterexample: for [2000000000, -2000000000, 5] the difference 2,000,000,000 minus -2,000,000,000 wraps to -294,967,296. The sort returned the list unchanged, out of order. Integer.compare(a, b) sorted it to [-2000000000, 5, 2000000000].
This Java version reads two counts from a HashMap<String, Integer> and compares them with ==.
Counterexample: two Integer objects holding 1,000 gave false, and two holding 100 gave true, because Java caches small values by default. Compare with equals, or copy the counts into int variables first.
A task asks for the words in alphabetical order with their counts. A hash map does not keep order, so counting is only half the job.
Sort the keys afterwards, or use an ordered map such as C++ std::map, which keeps keys sorted. Choose the tool by the order you need.
Your team lead brings three product changes. Each one changes the tool.
The team wants the top three words. Count with a map, then sort the entries by count, then by word. Sorting the distinct words costs O(d log d) for d distinct words, which is below n log n.
Rain and rain must count as one word. Convert each word to lower case before counting. This is one extra step inside the loop, and the class stays O(n).
The team asks how many different words appeared. The job is membership, so use a set. The answer is the size of the set, and the map is not needed.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you pick a tool for counting, membership and ordering, and name one place where two languages differ. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have practised it.
I count with a map, test membership with a set, and order with a sort and a key. Each language has all four.
I never rely on map order, so I write a tie rule. I use a comparator in Java, C++ and JavaScript, and I remember that the JavaScript default sort compares text.
I check the width of totals, because Java wraps at 2,147,483,647, and I use a stable sort when ties matter.
For counting I use a map from the item to its count, and I read the list once. That costs about n steps, against n squared if I scan again for every item. For membership I use a set, and for order I sort a copy with a key.
I keep each solution in the same steps in all four languages. Python uses a dict, Java a HashMap, C++ an unordered_map and JavaScript a Map.
I never rely on map order. Python and JavaScript keep insertion order, but Java and C++ promise none, so I write a tie rule.
In JavaScript I pass a comparator, because the default sort compares text. In C++ I use a stable sort when ties matter.
I use 64-bit totals when a count can pass two billion.
Checkpoint · Language toolkit cards
Q1/10 Which tool counts how often each word appears?
Answer: B
A map keeps one count for each word, and the list is read once.
Q2/10 What is the map type in Java?
Answer: B
Java uses HashMap. dict is Python, unordered_map is C++ and Map is JavaScript.
Q3/10 A list has 100,000 words. About how many checks does counting each word by scanning the whole list make?
Answer: C
Each of the 100,000 words scans 100,000 words.
Q4/10 Which languages keep map keys in insertion order?
Answer: A
Java's HashMap and C++'s unordered_map promise no order.
Q5/10 Two words tie for the highest count. How do you make the answer the same in every language?
Answer: B
Map order is not the same everywhere, so the tie rule must be in your code.
Q6/10 What does [10, 9, 1].sort() give in JavaScript?
Answer: B
The default sort compares items as text.
Q7/10 Which sort is not guaranteed to keep equal keys in input order?
Answer: C
std::stable_sort is the stable version in C++.
Q8/10 In Python, -7 // 2 gives what?
Answer: B
Python rounds down. Java, C++ and Math.trunc in JavaScript give -3.
Q9/10 What is the largest 32-bit integer plus 1 in Java?
Answer: C
Java integers wrap without an error.
Q10/10 A task asks how many different hostnames appear in a list. Which tool fits best?
Answer: B
The job is membership, so a set inserts each hostname once.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Busiest warehouse | Shop | Easy | Rows of an array, a sum for each row and a tie rule |
| 2 | Query word count | Search | Easy | Strings, stray spaces and a single pass |
| 3 | Sort tickets by priority then age | Bank | Medium | A sort with two keys and a tie-break |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.