SyntaxPilot
Courses/Low-Level Design/Lesson 87
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 87 of 90

Mock machine-coding round 1: Stack Overflow

timed mockQuestionAnswerCommentVoteTagreputation rulessearchbountymoderationinterviewer follow-upsself-review

These are the notes for Low-Level Design (LLD) episode 87, the first timed mock machine-coding round of the course: design Stack Overflow. We cover the time plan, Question, Answer, Comment, Vote and Tag, reputation rules, search, bounty, moderation, the interviewer follow-ups and a self-review.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. People and posts are made up.

Where the numbers come from: the reputation and bounty rules are taken from Stack Overflow's help pages, fetched on 14 November 2026: What is reputation? and What is a bounty?. The code is a simplified teaching model of those rules (for example, our daily cap only limits gains), not Stack Overflow's real code.

1. The problem: the college doubt-clearing class

  • A student raises a hand and asks a doubt: "Why does my loop never stop?" → a Question.
  • Seniors answer; others add small notes ("your i never changes!") → Answers and Comments.
  • The class nods at good answers; the teacher stars the best one → Votes and an accepted answer.
  • Over a semester, one senior earns everyone's trust and starts keeping order → Reputation and moderation.
Real life In the design
A doubt Question (title, body, tags)
A senior's reply Answer
A small note under a reply Comment
The topic written on the board ("loops", "Java") Tag
Nodding at a good answer A vote (UP / DOWN)
The teacher's star The accepted answer
Trust earned over a semester Reputation
"I'll give a chocolate for the best answer" A bounty
The trusted senior keeping order Moderation

2. What a timed mock is, and a 90-minute plan

A machine-coding round asks you to design and code a working program, with a demo, in a fixed time. A timed mock is practice under the same clock. The prompt: "Design Stack Overflow. 90 minutes. Runnable code with a demo."

Clarifying questions (questions you ask to pin down requirements) before any code:

  • Can users vote on answers too, or only questions? Can one person vote twice? Vote on their own post?
  • What are the reputation rules? Is there a floor or a daily limit?
  • Search by tag, by keyword, or both? How are results ordered?
  • Do we need bounties? Moderation? Comments?

A time plan (our suggestion; adjust to the round's length):

Minutes Do this
0-10 Requirements and clarifying questions; write them down
10-20 Entities and a class diagram
20-70 Core code: ask, answer, comment, vote, reputation, accept
70-85 Extensions: search, bounty, moderation
85-90 Run the demo, then a self-review

3. Attempt 1 (minute 15): maps of strings and numbers

In a panic, many people skip the design and write maps:

import java.util.*;
public class Main {                                        // minute 15 of the mock: "just make it work"
    static Map<String, String> questionAuthor = new HashMap<>();   // question id -> who asked
    static Map<String, Integer> votes = new HashMap<>();          // question id -> score
    static Map<String, Integer> rep = new HashMap<>();            // user -> reputation
    static void upvote(String user, String qid) {
        votes.merge(qid, 1, Integer::sum);
        rep.merge(questionAuthor.get(qid), 10, Integer::sum); }
    static void downvote(String user, String qid) {
        votes.merge(qid, -1, Integer::sum);
        rep.merge(questionAuthor.get(qid), -2, Integer::sum); }
    public static void main(String[] args) {
        rep.put("asha", 1);  rep.put("ravi", 1);
        questionAuthor.put("q1", "asha");                    // "How do I reverse a HashMap?"
        upvote("ravi", "q1");  upvote("ravi", "q1");  upvote("ravi", "q1");   // Ravi clicks three times
        upvote("asha", "q1");                               // Asha upvotes her own question
        System.out.println("q1 score: " + votes.get("q1") + ", asha's reputation: " + rep.get("asha"));
        questionAuthor.put("q2", "ravi");
        for (int i = 0; i < 3; i++) downvote("asha", "q2");    // three downvotes on Ravi's question
        System.out.println("ravi's reputation: " + rep.get("ravi"));
        upvote("ravi", "q3");                               // a question that doesn't exist
        System.out.println("all reputation: " + rep);
    }
}

Real output:

q1 score: 4, asha's reputation: 41
ravi's reputation: -5
all reputation: {null=10, asha=41, ravi=-5}

Why it failed

  • No objects. A vote is just +1, not tied to the voter: three clicks by Ravi plus Asha's own vote gave score 4 and 41 reputation.
  • Rules scattered. +10 here, -2 there, and no floor: Ravi reached -5.
  • No validation. A vote on the missing q3 looked up its author (null) and HashMap happily stored null=10. No crash, just quietly wrong data: the worst kind of bug.

4. The fix: entities, and vote rules inside the objects

Entities are the nouns of the problem that hold data and rules: User, Question, Answer, Comment, Tag, Vote.

  • Question and Answer share an author, a body, comments and votes, so both extend an abstract class Post (a class you can't create directly, only extend).
  • Votes are a Map<User, VoteType>: a map keeps one value per key, so each user has exactly one vote per post, and a second click replaces the first.
  • No self-votes: vote() refuses with a clear message.
  • Tag and Comment are records (short classes that only hold values).
import java.util.*;
enum VoteType { UP, DOWN }
class User { final String name;  int reputation = 1;  User(String n) { name = n; } }
record Tag(String name) { public String toString() { return name; } }
record Comment(User author, String text) {}
abstract class Post {                                       // what Question and Answer share
    final User author;  final String body;  final List<Comment> comments = new ArrayList<>();
    private final Map<User, VoteType> votes = new HashMap<>();          // one vote per user
    Post(User a, String b) { author = a;  body = b; }
    void vote(User voter, VoteType type) {
        if (voter == author) throw new IllegalArgumentException(voter.name + " cannot vote on their own post");
        votes.put(voter, type); }                                       // a second click replaces the first
    int score() { int s = 0;  for (VoteType v : votes.values()) s += v == VoteType.UP ? 1 : -1;  return s; } }
class Question extends Post {
    final String title;  final Set<Tag> tags;  final List<Answer> answers = new ArrayList<>();
    Question(User a, String t, String body, Set<Tag> tags) { super(a, body);  title = t;  this.tags = tags; }
    Answer answer(User a, String body) { Answer x = new Answer(a, body, this);  answers.add(x);  return x; } }
class Answer extends Post { final Question question;
    Answer(User a, String body, Question q) { super(a, body);  question = q; } }
public class Main { public static void main(String[] args) {
    User asha = new User("asha"), ravi = new User("ravi"), neha = new User("neha");
    Question q = new Question(asha, "How do I reverse a HashMap?", "keys to values?", Set.of(new Tag("java")));
    Answer a = q.answer(ravi, "Loop over entrySet() and put(value, key).");
    q.comments.add(new Comment(neha, "What if two keys have the same value?"));
    q.vote(ravi, VoteType.UP);  q.vote(ravi, VoteType.UP);  q.vote(neha, VoteType.UP);    // Ravi clicks twice
    a.vote(neha, VoteType.DOWN);  a.vote(neha, VoteType.UP);                // Neha changes her mind
    System.out.println(q.title + " " + q.tags + ": score " + q.score() + ", " + q.answers.size() + " answer, "
        + q.comments.size() + " comment; answer score " + a.score());
    q.vote(asha, VoteType.UP); } }

Real output:

How do I reverse a HashMap? [java]: score 2, 1 answer, 1 comment; answer score 1
Exception in thread "main" java.lang.IllegalArgumentException: asha cannot vote on their own post
    at Post.vote(Main.java:11)
    at Main.main(Main.java:29)
  • Score 2: Ravi's double click counted once, plus Neha's.
  • Answer score 1: Neha's down vote was replaced by her up vote.

5. Reputation rules, in one place

Reputation is a number that shows how much the community trusts you. The rules (from Stack Overflow's help page linked above):

Event Points
Your question is voted up +10
Your answer is voted up +10
Your answer is marked "accepted" +15 (and +2 to the person who accepts)
Your question or answer is voted down −2
You vote down an answer −1
You place a bounty − the full bounty amount
A bounty is awarded to your answer + the full bounty amount
One of your posts gets 6 spam or offensive flags −100
Floor Reputation never drops below 1 (everyone starts at 1)
Daily cap At most 200 a day from upvotes, downvotes and suggested edits (accepts and bounties are not capped)

Design: an enum (Rep) holds every rule with its points, and one ReputationService.apply() is the only place reputation changes. When the rules change, one file changes.

import java.util.*;
class User { final String name;  int reputation = 1, earnedToday = 0;  User(String n) { name = n; }
    public String toString() { return name + "=" + reputation; } }
record Post(User author, boolean isQuestion) {}
enum Rep {                                                   // the rules, in one place
    QUESTION_UPVOTED(10), ANSWER_UPVOTED(10), POST_DOWNVOTED(-2), DOWNVOTED_AN_ANSWER(-1),
    ANSWER_ACCEPTED(15), ACCEPTED_AN_ANSWER(2);
    final int points;  Rep(int p) { points = p; } }
class ReputationService {
    static final int DAILY_VOTE_CAP = 200;                   // from votes, per user, per day
    void apply(User u, Rep r, boolean capped) {
        int pts = r.points;
        if (capped && pts > 0) { pts = Math.min(pts, DAILY_VOTE_CAP - u.earnedToday);  u.earnedToday += pts; }
        u.reputation = Math.max(1, u.reputation + pts); }     // never below 1
    void upvoted(Post p) { apply(p.author(), p.isQuestion() ? Rep.QUESTION_UPVOTED : Rep.ANSWER_UPVOTED, true); }
    void downvoted(Post p, User voter) { apply(p.author(), Rep.POST_DOWNVOTED, true);
        if (!p.isQuestion()) apply(voter, Rep.DOWNVOTED_AN_ANSWER, false); }   // costs the voter 1
    void accepted(Post answer, User asker) { apply(answer.author(), Rep.ANSWER_ACCEPTED, false);
        if (asker != answer.author()) apply(asker, Rep.ACCEPTED_AN_ANSWER, false); } }
public class Main { public static void main(String[] args) {
    ReputationService rs = new ReputationService();
    User asha = new User("asha"), ravi = new User("ravi"), neha = new User("neha"), kiran = new User("kiran");
    Post q = new Post(asha, true), a = new Post(ravi, false), spam = new Post(kiran, false);
    rs.upvoted(q);  rs.upvoted(a);  rs.downvoted(spam, neha);  rs.accepted(a, asha);
    System.out.println("after one of each: " + List.of(asha, ravi, neha, kiran));
    for (int i = 0; i < 25; i++) rs.upvoted(a);              // a viral answer: 25 upvotes today
    System.out.println("25 more upvotes: " + ravi + ", earned from votes today: " + ravi.earnedToday);
} }

Real output:

after one of each: [asha=13, ravi=26, neha=1, kiran=1]
25 more upvotes: ravi=216, earned from votes today: 200
  • asha = 1 + 10 (question upvoted) + 2 (accepted an answer) = 13.
  • ravi = 1 + 10 (answer upvoted) + 15 (accepted) = 26.
  • neha paid −1 for downvoting an answer and kiran lost −2: both stay at the floor of 1.
  • 25 more upvotes would be +250, but the cap stops vote earnings at 200 today: 26 + 190 = 216.
  • Simplification: our cap only limits gains; the real cap counts the combination of upvotes, downvotes and suggested edits.

6. Search: a tag index and an inverted index

Scanning every title on every search gets slower as the site grows. Build indexes when a question is posted:

  • Tag index: tag → questions with that tag.
  • Inverted index: word → questions whose title contains it, like the index at the back of a textbook (word → pages).
  • A query like [java] hashmap means tag java AND word hashmap: look up both sets and keep the intersection (retainAll).
  • Rank by score, highest first.
import java.util.*;
record Question(int id, String title, Set<String> tags, int score) {
    public String toString() { return "#" + id + " (score " + score + ")"; } }
class SearchIndex {                                          // built when a question is posted, not per search
    private final Map<String, Set<Question>> byTag = new HashMap<>();     // "java" -> questions
    private final Map<String, Set<Question>> byWord = new HashMap<>();    // inverted index: word -> questions
    void add(Question q) {
        for (String t : q.tags()) byTag.computeIfAbsent(t, k -> new HashSet<>()).add(q);
        for (String w : q.title().toLowerCase().split("\\W+"))         // split on anything not a letter or digit
            byWord.computeIfAbsent(w, k -> new HashSet<>()).add(q); }
    List<Question> search(String query) {                    // "[java] hashmap": [tag], then words
        Set<Question> hits = null;
        for (String part : query.toLowerCase().split(" ")) {
            String key = part.replaceAll("[\\[\\]]", "");          // strip the brackets
            Set<Question> found = (part.startsWith("[") ? byTag : byWord).getOrDefault(key, Set.of());
            if (hits == null) hits = new HashSet<>(found); else hits.retainAll(found); }   // AND
        List<Question> list = new ArrayList<>(hits == null ? Set.of() : hits);
        list.sort(Comparator.comparingInt(Question::score).reversed());               // best first
        return list; } }
public class Main { public static void main(String[] args) {
    SearchIndex idx = new SearchIndex();
    idx.add(new Question(1, "How do I reverse a HashMap?", Set.of("java", "hashmap"), 12));
    idx.add(new Question(2, "HashMap vs TreeMap in Java", Set.of("java", "collections"), 40));
    idx.add(new Question(3, "Python dict like a HashMap?", Set.of("python"), 7));
    idx.add(new Question(4, "Why is my Java loop slow?", Set.of("java", "performance"), 3));
    System.out.println("hashmap        -> " + idx.search("hashmap"));
    System.out.println("[java] hashmap -> " + idx.search("[java] hashmap"));
    System.out.println("[java] slow    -> " + idx.search("[java] slow"));
    System.out.println("[rust]         -> " + idx.search("[rust]")); } }

Real output:

hashmap        -> [#2 (score 40), #1 (score 12), #3 (score 7)]
[java] hashmap -> [#2 (score 40), #1 (score 12)]
[java] slow    -> [#4 (score 3)]
[rust]         -> []
  • split("\\W+") splits on anything that isn't a letter, digit or underscore, so "HashMap?" becomes the word hashmap.
  • [rust] finds nothing: an empty list, not an error.

7. Bounty and moderation

Bounty: you offer some of your own reputation to attract a better answer. Rules (from Stack Overflow's bounty help page):

  • Amount 50 to 500, in steps of 50.
  • Can start 2 days after the question was asked.
  • Lasts 7 days, then a 24-hour grace period to award it manually.
  • The reputation is taken up front and is not refunded.
  • If you don't award it, the top-scored eligible answer (posted after the bounty started, score at least 2) gets half; otherwise nobody gets it.

Moderation keeps the site clean. A post that gets 6 spam or offensive flags is hidden and its author loses 100 reputation. Flags go in a Set<User>, so one user flagging twice counts once.

import java.util.*;
class User { final String name;  int rep;  User(String n, int r) { name = n;  rep = r; }
    public String toString() { return name + "=" + rep; } }
class Post { final User author;  final int postedOnDay;  boolean hidden;
    final Set<User> spamFlags = new HashSet<>();  Post(User a, int day) { author = a;  postedOnDay = day; } }
record Bounty(int amount, int startDay, User by) { int endDay() { return startDay + 7; } }   // lasts 7 days
class BountyService { final Map<Post, Bounty> open = new HashMap<>();
    void start(Post q, User by, int amount, int today) {
        if (amount < 50 || amount > 500 || amount % 50 != 0)
            throw new IllegalArgumentException("bounty must be 50-500, in steps of 50");
        if (today - q.postedOnDay < 2) throw new IllegalStateException("too early: wait 2 days after asking");
        if (by.rep < amount) throw new IllegalStateException(by.name + " has only " + by.rep + " reputation");
        by.rep -= amount;  open.put(q, new Bounty(amount, today, by)); }        // paid up front, not refunded
    void award(Post q, Post answer, int today) { Bounty b = open.remove(q);
        if (b == null || today > b.endDay() + 1) throw new IllegalStateException("no open bounty");  // 1 day grace
        answer.author.rep += b.amount(); } }
class Moderation { static final int HIDE_AT = 6;              // 6 spam flags hide a post
    void flagSpam(Post p, User flagger) {
        if (p.spamFlags.add(flagger) && p.spamFlags.size() == HIDE_AT) {      // a Set: one flag per user
            p.hidden = true;  p.author.rep = Math.max(1, p.author.rep - 100); } } }
public class Main { public static void main(String[] args) {
    User asha = new User("asha", 600), ravi = new User("ravi", 1), kiran = new User("kiran", 120);
    Post q = new Post(asha, 0), answer = new Post(ravi, 3), spam = new Post(kiran, 3);
    BountyService bounties = new BountyService();  Moderation mod = new Moderation();
    for (int[] t : new int[][] {{100, 1}, {120, 2}, {150, 2}})              // {amount, day}
        try { bounties.start(q, asha, t[0], t[1]);  System.out.println("bounty " + t[0] + " started, " + asha); }
        catch (RuntimeException e) { System.out.println("refused: " + e.getMessage()); }
    bounties.award(q, answer, 5);  System.out.println("awarded on day 5: " + ravi);
    User[] users = new User[7];  for (int i = 0; i < 7; i++) users[i] = new User("u" + i, 50);
    for (int i = 0; i < 8; i++) mod.flagSpam(spam, users[i % 7]);          // u0 flags twice
    System.out.println("spam hidden? " + spam.hidden + ", " + kiran + ", flags: " + spam.spamFlags.size()); } }

Real output:

refused: too early: wait 2 days after asking
refused: bounty must be 50-500, in steps of 50
bounty 150 started, asha=450
awarded on day 5: ravi=151
spam hidden? true, kiran=20, flags: 7
  • The day-1 attempt fails on timing before the amount is even checked; the order of checks decides which message the user sees.
  • Kiran: 120 − 100 = 20. Flags: 7 users, not 8: u0's second flag was ignored by the set.

8. The class diagram

User: name, reputation (never below 1)
Post (abstract): author, body, comments, votes = Map<User, VoteType> · vote() · score()
  ◁── Question: title, tags, answers, accepted · Answer: its question
Comment: author, text · Tag: name · VoteType: UP | DOWN
ReputationService + enum Rep: +10 / +10 / -2 / -1 / +15 / +2 · daily vote cap 200
SearchIndex: tag -> questions · word -> questions (inverted index) · AND, best score first
BountyService: 50-500 in steps of 50 · 2 days after asking · 7 days · Moderation: 6 flags hide

9. Interviewer follow-ups

Follow-up A good answer
Two votes at the same moment? ConcurrentHashMap for votes; update reputation atomically (in one step no other thread can interrupt), e.g. AtomicInteger or a lock per user.
Duplicate questions? Close one as a duplicate and link it to the original; search shows the original.
Badges ("first accepted answer")? Observer pattern: badge rules listen to events like AnswerAccepted.
Edit history? Keep a list of versions per post (each an immutable record with author and time).
Changing a vote? Undo the old vote's reputation effect, then apply the new one.
Millions of questions? The in-memory index becomes a real search engine and the maps a database. Say it; don't build it in 90 minutes.
Reputation-based privileges? A rule table: "can downvote at N reputation"; check it in vote().

10. The self-review

In the last five minutes, review your own work out loud, before the interviewer does:

  • ✓ Asked clarifying questions and wrote the requirements.
  • ✓ Found the entities first; Post shared by Question and Answer.
  • ✓ Rules in one place: the Rep enum, the vote map, the bounty checks.
  • ✓ Ran a demo with edge cases and clear errors.
  • ✗ Missing: thread safety, a cap that also counts downvotes, changing a vote's reputation, unit tests.

Naming what's missing shows judgment, which is what the round is really testing.

11. Common mistakes

Mistake What you see (real) Fix
Votes as a counter q1 score: 4 from two people Map<User, VoteType>
No self-vote check Asha upvotes her own question cannot vote on their own post
Reputation without a floor ravi's reputation: -5 Math.max(1, ...)
Looking up a missing id {null=10, asha=41, ravi=-5} Validate ids; fail loudly
Rules spread over many methods inconsistent points One Rep enum + one apply()
Scanning every title per search slow search Index on write
Flags in a List one user hides a post alone A Set<User>
Coding before asking the wrong product, built fast Minutes 0-10: clarify

Mini project: the whole site in one program

Everything together behind one facade class (StackOverflow, a single entry point that hides the parts: the Facade pattern from episode 30): join, ask, answer, comment, vote with reputation, accept, search (hidden spam left out), spam flags, bounty with days, and the error cases.

import java.util.*;

enum VoteType { UP, DOWN }
enum Rep {                                                    // every reputation rule in one place
    QUESTION_UPVOTED(10), ANSWER_UPVOTED(10), POST_DOWNVOTED(-2), DOWNVOTED_AN_ANSWER(-1),
    ANSWER_ACCEPTED(15), ACCEPTED_AN_ANSWER(2), SPAM_REMOVED(-100);
    final int points; Rep(int p) { points = p; }
}

class User {
    final String name; int reputation = 1, earnedToday = 0;
    User(String name) { this.name = name; }
    public String toString() { return name + "(" + reputation + ")"; }
}
record Tag(String name) { public String toString() { return name; } }
record Comment(User author, String text) {}

abstract class Post {
    private static int nextId = 1;
    final int id = nextId++;
    final User author; final String body; final int postedOnDay;
    final List<Comment> comments = new ArrayList<>();
    final Map<User, VoteType> votes = new HashMap<>();
    final Set<User> spamFlags = new HashSet<>();
    boolean hidden;
    Post(User author, String body, int day) { this.author = author; this.body = body; this.postedOnDay = day; }
    int score() { return (int) votes.values().stream().mapToInt(v -> v == VoteType.UP ? 1 : -1).sum(); }
    abstract boolean isQuestion();
}
class Question extends Post {
    final String title; final Set<Tag> tags; final List<Answer> answers = new ArrayList<>();
    Answer accepted; int bounty; int bountyEndsOnDay;
    Question(User a, String title, String body, Set<Tag> tags, int day) { super(a, body, day); this.title = title; this.tags = tags; }
    boolean isQuestion() { return true; }
    public String toString() { return "#" + id + " \"" + title + "\" " + tags + " score " + score(); }
}
class Answer extends Post {
    final Question question;
    Answer(User a, String body, Question q, int day) { super(a, body, day); question = q; }
    boolean isQuestion() { return false; }
}

class ReputationService {
    static final int DAILY_VOTE_CAP = 200;
    void apply(User u, Rep r, boolean fromVotes) {
        int pts = r.points;
        if (fromVotes && pts > 0) { pts = Math.max(0, Math.min(pts, DAILY_VOTE_CAP - u.earnedToday)); u.earnedToday += pts; }
        u.reputation = Math.max(1, u.reputation + pts);
    }
    void newDay(Collection<User> users) { for (User u : users) u.earnedToday = 0; }
}

class SearchIndex {
    private final Map<String, Set<Question>> byTag = new HashMap<>(), byWord = new HashMap<>();
    void add(Question q) {
        for (Tag t : q.tags) byTag.computeIfAbsent(t.name(), k -> new HashSet<>()).add(q);
        for (String w : q.title.toLowerCase().split("\\W+")) byWord.computeIfAbsent(w, k -> new HashSet<>()).add(q);
    }
    List<Question> search(String query) {
        Set<Question> hits = null;
        for (String part : query.toLowerCase().trim().split("\\s+")) {
            boolean tag = part.startsWith("[") && part.endsWith("]");
            String key = tag ? part.substring(1, part.length() - 1) : part;
            Set<Question> found = (tag ? byTag : byWord).getOrDefault(key, Set.of());
            if (hits == null) hits = new HashSet<>(found); else hits.retainAll(found);
        }
        List<Question> list = new ArrayList<>(hits == null ? Set.of() : hits);
        list.removeIf(q -> q.hidden);
        list.sort(Comparator.comparingInt(Question::score).reversed().thenComparingInt(q -> q.id));
        return list;
    }
}

class StackOverflow {                                         // the facade the demo talks to
    final Map<String, User> users = new LinkedHashMap<>();
    final ReputationService rep = new ReputationService();
    final SearchIndex index = new SearchIndex();
    int today = 0;

    User join(String name) { return users.computeIfAbsent(name, User::new); }
    Question ask(User u, String title, String body, String... tags) {
        Set<Tag> t = new LinkedHashSet<>(); for (String s : tags) t.add(new Tag(s));
        Question q = new Question(u, title, body, t, today); index.add(q); return q;
    }
    Answer answer(User u, Question q, String body) { Answer a = new Answer(u, body, q, today); q.answers.add(a); return a; }
    void comment(User u, Post p, String text) { p.comments.add(new Comment(u, text)); }

    void vote(User voter, Post p, VoteType type) {
        if (voter == p.author) throw new IllegalArgumentException(voter.name + " cannot vote on their own post");
        VoteType old = p.votes.put(voter, type);
        if (old == type) return;                              // the same click twice changes nothing
        if (old != null) throw new IllegalStateException("changing a vote: undo the old one first (left out to keep this short)");
        if (type == VoteType.UP) rep.apply(p.author, p.isQuestion() ? Rep.QUESTION_UPVOTED : Rep.ANSWER_UPVOTED, true);
        else { rep.apply(p.author, Rep.POST_DOWNVOTED, true); if (!p.isQuestion()) rep.apply(voter, Rep.DOWNVOTED_AN_ANSWER, false); }
    }
    void accept(User by, Answer a) {
        Question q = a.question;
        if (by != q.author) throw new IllegalArgumentException("only " + q.author.name + " can accept an answer");
        if (q.accepted != null) throw new IllegalStateException("an answer is already accepted");
        q.accepted = a;
        rep.apply(a.author, Rep.ANSWER_ACCEPTED, false);
        if (a.author != by) rep.apply(by, Rep.ACCEPTED_AN_ANSWER, false);
    }
    void startBounty(User by, Question q, int amount) {
        if (amount < 50 || amount > 500 || amount % 50 != 0) throw new IllegalArgumentException("bounty must be 50-500, in steps of 50");
        if (today - q.postedOnDay < 2) throw new IllegalStateException("too early: wait 2 days after asking");
        if (q.bounty > 0) throw new IllegalStateException("a bounty is already open");
        if (by.reputation <= amount) throw new IllegalStateException(by.name + " has only " + by.reputation + " reputation");
        by.reputation -= amount; q.bounty = amount; q.bountyEndsOnDay = today + 7;
    }
    void awardBounty(User by, Question q, Answer a) {
        if (q.bounty == 0 || today > q.bountyEndsOnDay + 1) throw new IllegalStateException("no open bounty");
        a.author.reputation += q.bounty; q.bounty = 0;
    }
    void flagSpam(User flagger, Post p) {
        if (p.spamFlags.add(flagger) && p.spamFlags.size() == 6 && !p.hidden) { p.hidden = true; rep.apply(p.author, Rep.SPAM_REMOVED, false); }
    }
    void nextDay() { today++; rep.newDay(users.values()); }
}

public class Main {
    public static void main(String[] args) {
        StackOverflow so = new StackOverflow();
        User asha = so.join("asha"), ravi = so.join("ravi"), neha = so.join("neha"), kiran = so.join("kiran");
        Question q1 = so.ask(asha, "How do I reverse a HashMap?", "keys become values", "java", "hashmap");
        Question q2 = so.ask(neha, "HashMap vs TreeMap in Java", "which one when?", "java", "collections");
        Question q3 = so.ask(kiran, "Cheap watches here", "buy now!!!", "java");
        Answer a1 = so.answer(ravi, q1, "Loop over entrySet() and put(value, key).");
        so.comment(neha, a1, "What if two keys have the same value?");
        so.vote(ravi, q1, VoteType.UP); so.vote(ravi, q1, VoteType.UP); so.vote(neha, q1, VoteType.UP);
        so.vote(asha, a1, VoteType.UP); so.vote(neha, a1, VoteType.UP); so.vote(asha, q2, VoteType.DOWN);
        so.accept(asha, a1);
        System.out.println("users: " + so.users.values());
        System.out.println("search [java] hashmap: " + so.index.search("[java] hashmap"));
        System.out.println("search [java]: " + so.index.search("[java]"));
        for (int i = 0; i < 6; i++) so.flagSpam(so.join("mod" + i), q3);
        System.out.println("after 6 spam flags, kiran: " + kiran + ", search [java]: " + so.index.search("[java]"));
        try { so.startBounty(neha, q2, 50); } catch (RuntimeException e) { System.out.println("bounty: " + e.getMessage()); }
        so.nextDay(); so.nextDay();
        try { so.startBounty(neha, q2, 50); } catch (RuntimeException e) { System.out.println("bounty: " + e.getMessage()); }
        asha.reputation += 300;                                // say Asha has earned more by now
        so.startBounty(asha, q1, 100);
        Answer a2 = so.answer(neha, q1, "Use a stream with Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey).");
        so.nextDay(); so.awardBounty(asha, q1, a2);
        System.out.println("after the bounty: " + so.users.values());
        for (Runnable bad : List.<Runnable>of(() -> so.vote(asha, q1, VoteType.UP), () -> so.accept(ravi, a1), () -> so.accept(asha, a2)))
            try { bad.run(); } catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); }
    }
}

Real output:

users: [asha(23), ravi(36), neha(1), kiran(1)]
search [java] hashmap: [#1 "How do I reverse a HashMap?" [java, hashmap] score 2, #2 "HashMap vs TreeMap in Java" [java, collections] score -1]
search [java]: [#1 "How do I reverse a HashMap?" [java, hashmap] score 2, #3 "Cheap watches here" [java] score 0, #2 "HashMap vs TreeMap in Java" [java, collections] score -1]
after 6 spam flags, kiran: kiran(1), search [java]: [#1 "How do I reverse a HashMap?" [java, hashmap] score 2, #2 "HashMap vs TreeMap in Java" [java, collections] score -1]
bounty: too early: wait 2 days after asking
bounty: neha has only 1 reputation
after the bounty: [asha(223), ravi(36), neha(101), kiran(1), mod0(1), mod1(1), mod2(1), mod3(1), mod4(1), mod5(1)]
IllegalArgumentException: asha cannot vote on their own post
IllegalArgumentException: only asha can accept an answer
IllegalStateException: an answer is already accepted
  • asha = 1 + 20 (two upvotes) + 2 (accepted) = 23; ravi = 1 + 20 + 15 = 36; neha's question got a downvote: floor 1.
  • After 6 flags, kiran's spam is hidden from search; kiran stays at the floor of 1.
  • Neha's bounty: first too early, then she can't afford 50.
  • Asha (now 323) offers 100 → 223; Neha's answer gets it → 101.
  • Interviewers love the last three lines: every rule refuses with a clear reason.

Practice

1. Ravi starts at 1. His answer gets 4 upvotes, 2 downvotes, and is accepted. Reputation?

Answer

1 + 40 − 4 + 15 = 52.

2. Add "only the asker can accept, and only once" to the code in section 4.

Answer
void accept(User by, Answer a) {
    if (by != a.question.author) throw new IllegalArgumentException("only the asker can accept");
    if (a.question.accepted != null) throw new IllegalStateException("already accepted");
    a.question.accepted = a;
}

3. Why does the search index get updated in add() (on write) and not in search()?

Answer

Questions are written once and searched many times. Doing the work on write makes every search a few map lookups instead of a scan of every title.

4. Is [java] hashmap an AND or an OR in our design? How would you add OR?

Answer

AND (retainAll, the intersection). For OR, use addAll (the union), e.g. for a query like hashmap or treemap.

5. How would you change vote() so a user can switch from DOWN to UP with correct reputation?

Answer

Look at the old vote: if it was DOWN, reverse its effect (+2 to the author, +1 back to the voter for an answer), then apply the UP (+10). Keeping each rule's opposite in the Rep enum (or storing what was applied) makes this exact.

6. A bounty of 75? A bounty on a 1-day-old question? A bounty of 500 by a user with 400?

Answer

75: refused (steps of 50). 1 day old: refused (2 days). 500 with 400 reputation: refused (not enough reputation).

Quick quiz

Ravi starts at 1. His answer gets 3 upvotes and 1 downvote, and the asker accepts it (+10 up, −2 down, +15 accepted). Reputation? (a) 44 (b) 46 (c) 48 (d) 60

Answer

(a) 44. 1 + 30 − 2 + 15. The −1 for downvoting is paid by the voter, not by Ravi.

Interview questions

  1. What entities does Stack Overflow need? User, Question, Answer, Comment, Tag, Vote (and Bounty, Flag as extensions).
  2. Why an abstract Post? Question and Answer share author, body, comments, votes and scoring.
  3. How do you stop double votes? Map<User, VoteType> per post: one entry per user.
  4. Where do reputation rules live? In one enum and one service method, so a rule change touches one place.
  5. How is reputation kept sane? A floor of 1 and a daily cap on vote earnings.
  6. How does search work? A tag index and an inverted index built on write; intersect for AND; sort by score.
  7. How do bounties work? 50-500 in steps of 50, start 2 days after asking, last 7 days, paid up front.
  8. How does moderation work? Flags from distinct users; at 6 spam flags the post is hidden and the author loses 100.
  9. How do you handle concurrent votes? Concurrent maps and atomic reputation updates (or a lock per user).
  10. What do you do in the last five minutes? Run the demo and give a self-review: what's done, what's missing.

Glossary

Term Meaning, with an example
Machine-coding round An interview round where you design and code a working program in a fixed time
Timed mock Practice under the same clock as the real round
Clarifying questions Questions that pin down requirements: "can one person vote twice?"
Requirements What the program must do, written down before coding
Entity A noun of the problem with data and rules: Question
Question A post with a title, body and tags, asking for help
Answer A post that replies to one question
Comment A short note under a post
Vote A user's UP or DOWN on a post; one per user per post
Score Upvotes minus downvotes
Tag A topic label on a question: java
Accepted answer The answer the asker marks as solving the problem
Reputation A number showing how much the community trusts you
Reputation rules How many points each event gives or takes: +10, −2, +15
Floor The minimum value: reputation never drops below 1
Daily cap The most you can earn in a day from votes: 200
Abstract class A class you can't create directly: Post
record A short class that only holds values: Tag, Comment
enum A type with a fixed list of values: VoteType, Rep
Map / HashMap A key → value table; one value per key
Set / HashSet A collection with no duplicates
Search Finding questions by tag and words
Index A lookup table built ahead of time to make search fast
Inverted index A map from each word to the items that contain it
Intersection (AND) Items present in both sets: retainAll
Bounty Reputation offered to attract a better answer
Grace period Extra time after the bounty ends to award it: 24 hours
Moderation Keeping the site clean: flags, hiding, penalties
Flag A user's report that a post is spam or offensive
Facade One simple class that fronts many parts: StackOverflow
Observer pattern Objects that listen for events: badges on AnswerAccepted
Atomic update A change that happens in one step no other thread can interrupt
ConcurrentHashMap A HashMap that's safe to use from many threads
Interviewer follow-ups Questions asked after your demo to test depth
Self-review Your own honest review of what's done and what's missing
IllegalArgumentException Java's exception for bad input: cannot vote on their own post
IllegalStateException Java's exception for "not allowed now": too early: wait 2 days after asking

Summary

  • A timed mock starts with clarifying questions and a time plan, not with code.
  • Maps of strings and numbers at minute 15 gave a score of 4 from two people, reputation of −5, and points for a user called null.
  • Entities fixed it: Question and Answer extend Post, with Comment, Tag and a Vote map that allows one vote per user and no self-votes.
  • Reputation rules live in one enum and one service, with a floor of 1 and a daily cap of 200 from votes.
  • Search uses a tag index and an inverted index, intersected and ranked by score.
  • Bounty (50-500, 2 days, 7 days) and moderation (6 flags hide a post, −100) enforce their rules with clear reasons.
  • Finish with the interviewer follow-ups and an honest self-review.
  • Next episode: mock round 2: a live cricket scoreboard.