Skip to content
Zeni Study
  • Pages
    • Learn Python In 7 Days
      • Day 1 : Variable + if/else
      • Day 2: Loops
      • Day 3 : Array + String
      • Day 4 — Functions
      • Day 5 — Dictionaries - Hashmap
      • Day 6 — Files & Errors
      • Day 7 — Mini Project & Programmer Thinking
    • Machine Coding:
      • Day 1 — Bank account + Wallet :
      • Day 2 : RateLimiter + seat booking
      • Day 3 : Library Management + Classroom Attendance System
      • Day 4 : Bank account and notification system.
      • Day 5 : Key-value and payment processor.
      • icon picker
        Day 6 : Discount engine + Seat booking( in depth)
      • Day 7: Parking lot System :
    • Machine coding extended:
      • Day 7.5 — Parking Lot (Constraint-Heavy Variant)
      • Day 8 : Order + Payment System
      • Day 8 — Extension Round (Mid-Interview Change)
      • Day 9 — Ticket Booking with Expiry (Simulated Time)
      • Day 9 — Extension Round (Seat Lock Ownership + Forced Unlock)
    • SQL + DB Thinking course
      • Day 1 — Tables, Rows & Thinking in Data
      • Day 2 — Relationships & Foreign Keys (Thinking in Connections)
      • Day 3 — Filtering, Aggregation & Answering Data Questions
      • Day 4 — JOINs (Combining Tables the Right Way)
      • Day 5 — Subqueries, EXISTS & NOT EXISTS (Thinking in Layers)
      • Day 6 — Indexes, Constraints & How Databases Think
      • Day 7 — Full SQL Interview Simulation (SDE-1 Ready)
      • Extended Day 1 — Core Business Systems (Deep Practice)
      • Extended Day 2 — Booking & Platform Systems (High-Depth Practice)
      • Extended Day 3 — Content & Learning Platforms (Capstone Practice)
    • LLD: Java
      • DAY 1 — Core Foundations (SDE-2 Level)
      • DAY 2 — State, Time & Domain Correctness
      • DAY 3 — Extensibility & Failure Handling (SDE-2 Core Signal)
      • DAY 4 — Concurrency, Scheduling & Consistency (SDE-2 Critical)
      • DAY 5 — Workflow Design & Config-Driven Systems (SDE-2+)
      • DAY 6 — Eventing & Usage-Based Systems (Advanced SDE-2)
      • DAY 7 — Interview Simulation (Hard, Production-Grade)
      • Hidden Edge Cases Interviewers Expect (Day-wise)
      • Detailed Testing file:
    • Assignment:
      • If else Practice Set

Day 6 : Discount engine + Seat booking( in depth)

Today is the most important and hardest day.
This is where most SDE-1 candidates fail machine coding rounds — not because of syntax, but because of complex rules + state transitions.

🟢 Day 6 — Constraint-Heavy Problems & State Transitions

🎯 Day 6 Objective

By the end of Day 6, the candidate should be able to:
Implement multiple rules simultaneously
Handle state transitions correctly
Enforce constraints without missing edge cases
Write logic that survives many method calls
Stay calm under complex requirements
Today is about precision under pressure.

1️⃣ Teaching Script — What to Say

Start with This Interview Reality

“Most machine coding problems are not hard because of logic. They are hard because many small rules interact.”
Common failure reasons:
Forgetting one constraint
Allowing invalid transitions
Resetting state incorrectly
Mixing responsibilities
Your goal is not clever code. Your goal is correct behavior.

2️⃣ Core Idea of Day 6

State + Rules + Time = Complexity
State changes over time
Rules restrict how state can change
Every method call must respect current state
🧠 You must ask: “Is this transition allowed right now?”

3️⃣ Small Code to Understand (Very Important)

Example — Simple Ticket Lock

class Ticket:
def __init__(self):
self.locked = False

def lock(self) -> bool:
if self.locked:
return False
self.locked = True
return True

def unlock(self) -> bool:
if not self.locked:
return False
self.locked = False
return True
Key idea:
Same method behaves differently depending on state
You must always check current state first

4️⃣ Mandatory Warm-up Practice

Task

Implement:
Class: PowerSwitch

Methods:
- turn_on() → bool
- turn_off() → bool
- is_on() → bool
Rules:
Cannot turn ON if already ON
Cannot turn OFF if already OFF
👉 This reinforces state-dependent behavior.

5️⃣ Machine Coding Rules (Day 6 Rules)

Read all constraints before coding
Track state explicitly
Validate before mutating state
Never assume default behavior
Return values strictly as required

6️⃣ Main Problem 1 — Ticket Booking with Seat Locking

Problem Statement

You are implementing a ticket booking system.
Each seat can be:
FREE
LOCKED
BOOKED
Only certain transitions are allowed.

Class Definition (DO NOT MODIFY)

class Seat:
def __init__(self, seat_id: str):
pass

def lock(self) -> bool:
pass

def book(self) -> bool:
pass

def unlock(self) -> bool:
pass

def get_state(self) -> str:
pass

Allowed State Transitions

Current State
Action
Result
Return
FREE
lock
LOCKED
True
FREE
book
BOOKED
True
LOCKED
book
BOOKED
True
LOCKED
unlock
FREE
True
BOOKED
any
False
There are no rows in this table
All other transitions → False.

Initial State

Seat starts as FREE

get_state()

Return one of: "FREE", "LOCKED", "BOOKED"

Example

seat = Seat("A1")

seat.lock() # True → LOCKED
seat.book() # True → BOOKED
seat.unlock() # False
seat.get_state() # "BOOKED"

What This Tests

Multi-state logic
Correct transition handling
Rejecting invalid actions

7️⃣ Main Problem 2 — Rule-Based Discount Engine

Problem Statement

Implement a discount engine that applies rules in sequence.
Each discount can be applied only once.

Class Definition (DO NOT MODIFY)

class DiscountEngine:
def __init__(self, original_price: int):
pass

def apply_coupon(self, code: str) -> bool:
pass

def apply_loyalty_discount(self) -> bool:
pass

def get_price(self) -> int:
pass

Requirements

Initial
Store original price
Current price starts as original
apply_coupon(code)
Valid coupon codes:
"SAVE10" → 10% off
"SAVE20" → 20% off
Coupon can be applied only once
Invalid or repeated coupon → False
Price should be updated accordingly
apply_loyalty_discount()
Can be applied only once
Gives flat ₹100 off
Price should not go below 0
Re-applying → False
get_price()
Return current price

Example

d = DiscountEngine(1000)

d.apply_coupon("SAVE10") # True → price 900
d.apply_coupon("SAVE10") # False
d.apply_loyalty_discount() # True → price 800
d.apply_loyalty_discount() # False

8️⃣ No-Guess Hints

Use string constants for state
Track applied discounts using booleans
Always validate before updating price
Avoid recomputing from original price
Clamp price at minimum 0

9️⃣ Evaluation Checklist

Correct solution must:
✅ Handle all state transitions
✅ Enforce one-time rules
✅ Reject invalid operations
✅ Preserve state across calls
✅ Return correct values
✅ Pass all edge cases

🔟 Reflection (Candidate Must Answer)

Why is explicit state tracking important?
What breaks if invalid transitions are allowed?
Why must discounts be applied only once?
How do multiple rules interact here?

⭐ Day 6 Golden Rule

Most bugs come from forgetting what state you’re in.

🧪 Day 6 — Test File

📁 Folder Structure

day6/
├── solution.py
└── test_day6.py

📄 (Given to Candidate)

class Seat:
def __init__(self, seat_id: str):
pass

def lock(self) -> bool:
pass

def book(self) -> bool:
pass

def unlock(self) -> bool:
pass

def get_state(self) -> str:
pass


class DiscountEngine:
def __init__(self, original_price: int):
pass

def apply_coupon(self, code: str) -> bool:
pass

def apply_loyalty_discount(self) -> bool:
pass

def get_price(self) -> int:
pass

📄 test_day6.py (Evaluator File)

from solution import Seat, DiscountEngine


def test_seat_states():
print("Running Seat state tests...")

seat = Seat("A1")

assert seat.get_state() == "FREE"
assert seat.lock() is True
assert seat.get_state() == "LOCKED"

assert seat.unlock() is True
assert seat.get_state() == "FREE"

assert seat.book() is True
assert seat.get_state() == "BOOKED"

assert seat.lock() is False
assert seat.unlock() is False
assert seat.book() is False

print("✅ Seat state tests passed")


def test_discount_engine():
print("Running DiscountEngine tests...")

d = DiscountEngine(1000)

assert d.get_price() == 1000

assert d.apply_coupon("SAVE10") is True
assert d.get_price() == 900

assert d.apply_coupon("SAVE10") is False
assert d.apply_coupon("INVALID") is False

assert d.apply_loyalty_discount() is True
assert d.get_price() == 800

assert d.apply_loyalty_discount() is False

d2 = DiscountEngine(50)
assert d2.apply_loyalty_discount() is True
assert d2.get_price() == 0

print("✅ DiscountEngine tests passed")


if __name__ == "__main__":
test_seat_states()
test_discount_engine()

print("\n🎉 ALL DAY 6 TESTS PASSED SUCCESSFULLY")

🏁 What Day 6 Achieves

After Day 6, the candidate can:
Handle complex rule systems
Manage multi-state objects
Avoid illegal transitions
Stay composed under heavy requirements

 
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.