Election process concept in MongoDB - Time & Space Complexity
When we look at an election process in a database, we want to know how long it takes as more candidates or voters join.
We ask: How does the work grow when the election gets bigger?
Analyze the time complexity of the following code snippet.
// Find all candidates
const candidates = db.candidates.find({});
// Count votes for each candidate
candidates.forEach(candidate => {
const voteCount = db.votes.countDocuments({ candidateId: candidate._id });
print(`Candidate ${candidate.name} has ${voteCount} votes.`);
});
This code finds all candidates and counts how many votes each one has.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each candidate and counting votes.
- How many times: Once for each candidate in the list.
Explain the growth pattern intuitively.
| Input Size (n candidates) | Approx. Operations |
|---|---|
| 10 | Counting votes 10 times |
| 100 | Counting votes 100 times |
| 1000 | Counting votes 1000 times |
Pattern observation: The work grows directly with the number of candidates. More candidates mean more vote counts to do.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the number of candidates grows.
[X] Wrong: "Counting votes for all candidates is always fast and does not depend on the number of candidates."
[OK] Correct: Each candidate requires a separate count, so more candidates mean more counting work.
Understanding how work grows with data size helps you explain your code clearly and shows you think about efficiency in real projects.
"What if we stored the vote counts inside each candidate document instead of counting every time? How would the time complexity change?"