Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
A book of n pages can be opened to page p by turning sheets from the front or from the back, and you want the smaller of those two counts. Turning from the front costs p/2 sheets; turning from the back costs n/2 − p/2 sheets. The answer is min(p/2, n/2 − p/2) using integer division. It is O(1) — no loop needed.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you can translate a physical 'flip the book' description into integer arithmetic, correctly model that pages are paired two-per-sheet, and spot the O(1) closed form instead of simulating turns.
Where candidates slip
Forgetting integer (floor) division and treating page 1 as if it shared a sheet with page 2, which shifts every count by one. Or simulating flips in a loop when a formula exists.
How to stand out
State the sheet model out loud ('two pages per sheet, page 1 sits alone'), derive front = p/2 and back = n/2 − p/2 from it, and explain why integer division is exactly the floor you want.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewFewest sheet turns to reach page pReachable from both ends?NoYesExplore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
Simulation — Flip Sheets One at a Time
1Hint 1Explore hintHide hint
The most literal model: start looking at the opening sheet and flip forward one sheet at a time until page p appears on the visible spread. Count the flips.
2Hint 2Explore hintHide hint
After `t` flips from the front, the visible pages are 2t and 2t+1. So you stop flipping the moment 2t+1 is no longer less than p.
3Hint 3Explore hintHide hint
Once you know the front count, the back count is total sheets minus front: n/2 − front. Return the smaller of the two.
A · Core idea
This is the version you would act out with a real book: open to the first sheet, then turn forward one sheet at a time, counting, until page p is staring back at you.
Modelling a single flip. After t flips from the front, the spread in front of you shows pages 2t and 2t+1. The opening sheet (t = 0) shows page 1 on the right. The next flip (t = 1) shows pages 2 and 3, and so on. Page p is visible exactly when 2t <= p <= 2t+1, so you keep flipping while the right-hand page 2t+1 is still less than p.
Deriving the back count without a second loop. The book has n / 2 sheets you could turn in total. If reaching p from the front took front flips, then reaching the same sheet from the back takes the leftover sheets: n/2 − front. You do not need to simulate the back separately — the two counts are complementary.
Why this is the version you replace. The loop runs up to about n/4 times, which for n = 10⁵ is tens of thousands of iterations to compute a number you can write in closed form. It is correct, but every iteration is re-deriving p / 2 the slow way. Mention it to show you understand the mechanics, then collapse it.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 6, p = 2Interactive diagram
Flipping forward one sheet at a time
front = 0Each node is a spread; the loop stops when page p first appears.
1C · Code with teaching comments
Reference implementation previewpublic int pageCount(int n, int p) { int front = 0; while (2 * front + 1 < p) { // flip forward until page p is on the spread front++; }Explore the full codeHide the full code
D · Why it works and complexityO(n) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
The front loop is just computing p / 2 one increment at a time, and the back count is the complement n/2 − p/2. Seeing that the loop has a closed form is the whole point — say it, then delete the loop.
ComplexityO(n) time, O(1) space — In the worst case page p is near the middle, so the loop runs about p/2 ≈ n/4 times — linear in n. Only a couple of counters are stored, so O(1) space.
E · Edge cases and pitfalls3Looping at all — this O(n) walk only re-derives p/2 the slow way.Explore edge casesHide edge cases
Pitfalls
- Looping at all — this O(n) walk only re-derives p/2 the slow way.
- Stopping the loop one flip late by comparing the left page (2*front) instead of the right page (2*front+1).
- Computing the back count with a second, separate loop instead of the complement n/2 − front.
Approach 2 of 2 · Optimal
Direct Formula — min(p/2, n/2 − p/2) (Optimal)
1Hint 1Explore hintHide hint
You never need to flip. The sheet that holds page p is fixed: it is sheet number p/2 counting from the front (integer division).
2Hint 2Explore hintHide hint
The book has n/2 sheets total, so the same sheet sits n/2 − p/2 turns away from the back.
3Hint 3Explore hintHide hint
The answer is just the smaller of those two distances: min(p/2, n/2 − p/2). No loop, two divisions and a min.
A · Core idea
Skip the flipping entirely and compute the two distances directly.
Why page p lives on sheet p/2. Because page 1 opens alone, the pairing runs 1 | 2-3 | 4-5 | 6-7. Integer division by 2 maps every page to its sheet: 1/2 = 0, 2/2 = 1, 3/2 = 1, 4/2 = 2, 5/2 = 2. The floor is doing real work here — pages 2 and 3 must collapse to the same sheet, which only happens if you truncate rather than round. So the sheets you turn from the front to reach page p is exactly p / 2.
Why the back distance is n/2 − p/2. The total number of sheets you could ever turn, front to back, is n / 2 (integer division, which correctly handles an odd final page). If page p is p/2 sheets in from the front, then it is the complement, n/2 − p/2, sheets in from the back. The two distances always sum to the total sheet count.
Why the minimum is the answer. You are free to start from whichever cover is closer, so you take the smaller of the front and back distances. That is the entire algorithm: min(p/2, n/2 − p/2).
Why this beats the loop. It produces the same number in three arithmetic operations instead of up to n/4 iterations. For an interview, writing the closed form signals that you modelled the structure instead of brute-forcing it.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 5, p = 4How to read it:The target sheet splits the book; you take whichever side is shorter.
0C · Code with teaching comments
D · Why it works and complexityO(1) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
The front distance and back distance are complements that sum to n/2, so once you have one you get the other for free. The floor in p / 2 is not a rounding convenience — it is the exact operation that pairs two pages onto one sheet.
ComplexityO(1) time, O(1) space — Two integer divisions, one subtraction, one comparison — a constant amount of work regardless of n. O(1) time and O(1) space.
E · Edge cases and pitfalls6n = 1, p = 1 — from_front = 0, total sheets = 0, from_back = 0. min(0, 0) = 0 — the page is already open.Explore edge casesHide edge cases
Edge cases handled
n = 1, p = 1from_front = 0, total sheets = 0, from_back = 0. min(0, 0) = 0 — the page is already open.n = 4, p = 4from_front = 2, total sheets = 2, from_back = 0 → 0. The last page is reached instantly from the back.n = 5, p = 3from_front = 1, total sheets = 2, from_back = 1 → min(1, 1) = 1. Both sides tie; either works.
Pitfalls
- Using floating-point or rounding division instead of integer floor — pages 2 and 3 must collapse onto the same sheet.
- Computing total sheets as (n+1)/2 or n − 1 instead of n/2 — only n/2 matches the pairing.
- Returning the front distance alone and forgetting the book can be opened from the back.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic int pageCount(int n, int p) { int fromFront = p / 2; int fromBack = n / 2 - p / 2; return Math.min(fromFront, fromBack); }Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1Rounding instead of flooring
Pages 2 and 3 share sheet 1. Only integer (floor) division collapses both onto sheet 1; rounding up sends page 3 to sheet 2 and shifts every count.
Explore the code comparisonHide the code comparison
Rounding instead of flooring
Pages 2 and 3 share sheet 1. Only integer (floor) division collapses both onto sheet 1; rounding up sends page 3 to sheet 2 and shifts every count.
Don't write this
from_front = math.ceil(p / 2) # page 3 wrongly lands on sheet 2Write this instead
from_front = p // 2 # floor: pages 2 and 3 both map to sheet 12Looping when a formula exists
Walking sheet by sheet is O(n) and only re-derives p/2. The interviewer is checking whether you see the closed form.
Explore the code comparisonHide the code comparison
Looping when a formula exists
Walking sheet by sheet is O(n) and only re-derives p/2. The interviewer is checking whether you see the closed form.
Don't write this
int front = 0;
while (2 * front + 1 < p) front++; // O(n) re-derivation of p/2Write this instead
int front = p / 2; // O(1) closed form3Wrong total-sheet count
The book has n/2 sheets. Using n − 1 or (n+1)/2 breaks the back distance, especially when n is odd.
Explore the code comparisonHide the code comparison
Wrong total-sheet count
The book has n/2 sheets. Using n − 1 or (n+1)/2 breaks the back distance, especially when n is odd.
Don't write this
int back = (n - 1) - p / 2; // overcounts sheetsWrite this instead
int back = n / 2 - p / 2; // n/2 is the true sheet countRevise
Carry the pattern into the interview
Pattern to remember
Count from both ends, take the minimum
Code pattern to memorize
front = p / 2
back = n / 2 - p / 2
return min(front, back) // integer division throughoutRules to remember
- 1Pages come in sheets of two: page 1 is alone on the opening sheet, then 2-3, 4-5, and so on. That is why every count divides by 2.
- 2Sheets to reach page p from the front is exactly
p / 2with integer division —floor, never rounding up. - 3Total sheets in the book is
n / 2(integer division), so sheets from the back isn / 2 - p / 2. - 4Compute both directions and return the smaller — the whole problem is one
minof two integer divisions. - 5Do not simulate page flips in a loop. Reaching for a
whilehere signals you missed the closed-form answer.
Use this pattern when
- You can approach a target from two ends and want the cheaper side
- Items are grouped in fixed-size chunks (here, two pages per sheet)
- The phrase 'minimum number of turns / steps' over a linear layout
- An O(1) closed form exists and a loop would only re-derive it
Choose another pattern when
- Chunk size varies per step → you actually need a loop or DP
- You must return the sequence of turns, not just the count → simulate
- The structure is a tree or graph, not a flat line → BFS/DFS instead
- Pages are not paired in twos → the /2 assumption breaks
Interview takeaway
When you can reach a target from either end of a fixed structure, the answer is almost always min(distance from front, distance from back). Drawing Book is the cleanest example: two pages per sheet turns the whole thing into min(p/2, n/2 − p/2) with zero looping.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternReach-from-both-ends with a fixed chunk size. Whenever a target on a linear structure can be approached from either side and each step covers a constant amount, the answer collapses to min(distance from front, distance from back). Here two pages per sheet gives min(p/2, n/2 − p/2) in O(1).
Practice queueDirect variations and pattern siblings
Direct follow-ups
- Bon Appétit (Bill Division)Coming soonAnother O(n) arithmetic-modelling problem — compute a fair share, compare to what was charged.
- Number Line JumpsClosed-form O(1) reasoning again — decide whether two movers ever coincide using divisibility.
- Day of the ProgrammerTranslate a real-world counting rule (calendars) into careful integer arithmetic.