Build a Weekly Schedule Grid
Data Structure DesignModel answerLast updated
Construct an interactive 7-day schedule grid with hour slots, allowing users to add titled events via a clean, state-driven dialog without duplicate data sources.
Create a weekly calendar component that displays a 7-day schedule breakdown divided into 1-hour time blocks (00:00 to 23:00).
Core Functionality
- Grid Layout: Display 7 daily columns across 24 hourly rows.
- Cell Selection: Clicking any individual cell (a specific day and hour) triggers a modal input dialog.
- Event Creation: The modal allows the user to input an event title. Upon submission, the event must render inside the chosen slot on the grid.
- Clean Architecture: The component must maintain a single source of truth for all schedule data. UI views and lookup indexes should be dynamically calculated rather than manually mirrored across multiple state containers.
Expected Deliverable
Provide a component implementation (preferably in React) along with an explanation of your state management decisions, complexity metrics, and handling of UX edge cases.
Hints
Hint 1
Avoid keeping a separate 2D grid matrix in React state alongside your raw events list; calculate cell contents on demand or memoize an index map from the events array.
Hint 2
Represent modal visibility using a nullable selected slot state (e.g., `{ dayIndex, hour } | null`) rather than a disconnected boolean toggle.
Hint 3
Isolate draft input strings inside the modal dialog component to prevent unnecessary parent re-renders while typing.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Approach
When building an interactive matrix UI, the primary challenge is state design. A common anti-pattern is maintaining both an events array and a 2D matrix (grid[7][24]) in state, synchronizing them on every change. This introduces redundant sources of truth that easily drift out of sync.
The optimal approach relies on single-source-of-truth state modeling:
events: An array containing canonical event objects ({ id, day, hour, title }).activeSlot: A state object ({ day, hour } | null) tracking which cell's dialog is currently active.
All view structures (such as matching events to cells) are derived dynamically using memoization.
+--------------------------------------------------------+
| State |
| events: [{ id, day, hour, title }] |
| activeSlot: { day: 1, hour: 9 } | null |
+--------------------------------------------------------+
|
v
useMemo(() => buildIndex(events))
|
v
+--------------------------------------------------------+
| Derived View (Map) |
| "1:9" -> [{ id, day: 1, hour: 9, title: "Standup" }] |
+--------------------------------------------------------+
Key Design Decisions
- Memoized Hash Index: To avoid running an $O(E)$ filter over every cell during render (which would take $O(7 \times 24 \times E)$ total), we compile
eventsinto aMap<string, Event[]>indexed by"day:hour". Lookups per cell become $O(1)$. - Nullable Modal State: Setting
activeSlottonullhides the dialog. Setting it to{ day, hour }opens it. This eliminates the risk of anisDialogOpenboolean getting out of sync with the target slot. - Encapsulated Draft Input: Unsaved text input lives inside the local state of the
EventDialogcomponent. Typing triggers re-renders only within the modal, preserving performance across the main grid.
Solution Implementation (React)
import React, { useState, useMemo } from "react";
const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const HOURS = Array.from({ length: 24 }, (_, i) => i);
const makeSlotKey = (day, hour) => `${day}:${hour}`;
const formatTimeLabel = (hour) => {
const period = hour >= 12 ? "PM" : "AM";
const displayHour = hour % 12 === 0 ? 12 : hour % 12;
return `${displayHour}:00 ${period}`;
};
export default function WeeklyCalendar() {
const [events, setEvents] = useState([]);
const [activeSlot, setActiveSlot] = useState(null);
// Derive lookup map for O(1) cell access
const eventsBySlot = useMemo(() => {
const map = new Map();
for (const item of events) {
const key = makeSlotKey(item.day, item.hour);
if (!map.has(key)) {
map.set(key, []);
}
map.get(key).push(item);
}
return map;
}, [events]);
const handleCreateEvent = (slot, title) => {
const newEntry = {
id: crypto.randomUUID(),
day: slot.day,
hour: slot.hour,
title: title.trim(),
};
setEvents((prev) => [...prev, newEntry]);
setActiveSlot(null);
};
return (
<div style={{ fontFamily: "sans-serif", maxWidth: 1000, margin: "0 auto" }}>
<h2>Weekly Schedule</h2>
{/* Grid Container */}
<div
style={{
display: "grid",
gridTemplateColumns: "80px repeat(7, 1fr)",
gap: 1,
backgroundColor: "#ccc",
border: "1px solid #ccc",
}}
>
{/* Header Row */}
<div style={headerStyle}>Time</div>
{DAYS.map((dayName) => (
<div key={dayName} style={headerStyle}>
{dayName}
</div>
))}
{/* Hour Rows */}
{HOURS.map((hour) => (
<React.Fragment key={hour}>
<div style={timeLabelStyle}>{formatTimeLabel(hour)}</div>
{DAYS.map((_, dayIndex) => {
const slotKey = makeSlotKey(dayIndex, hour);
const cellEvents = eventsBySlot.get(slotKey) || [];
return (
<button
key={slotKey}
type="button"
aria-label={`${DAYS[dayIndex]} ${formatTimeLabel(hour)}`}
onClick={() => setActiveSlot({ day: dayIndex, hour })}
style={cellStyle}
>
{cellEvents.map((evt) => (
<div key={evt.id} style={eventChipStyle}>
{evt.title}
</div>
))}
</button>
);
})}
</React.Fragment>
))}
</div>
{/* Creation Modal */}
{activeSlot && (
<EventModal
slot={activeSlot}
onSave={handleCreateEvent}
onClose={() => setActiveSlot(null)}
/>
)}
</div>
);
}
function EventModal({ slot, onSave, onClose }) {
const [draftTitle, setDraftTitle] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (draftTitle.trim()) {
onSave(slot, draftTitle);
}
};
return (
<div style={overlayStyle} onClick={onClose}>
<div
style={modalStyle}
onClick={(e) => e.stopPropagation()}
role="dialog"
aria-modal="true"
>
<h3>
Add Event: {DAYS[slot.day]} at {formatTimeLabel(slot.hour)}
</h3>
<form onSubmit={handleSubmit}>
<input
type="text"
autoFocus
placeholder="Event title"
value={draftTitle}
onChange={(e) => setDraftTitle(e.target.value)}
style={{ width: "100%", padding: 8, boxSizing: "border-box" }}
/>
<div style={{ marginTop: 12, textAlign: "right" }}>
<button type="button" onClick={onClose} style={{ marginRight: 8 }}>
Cancel
</button>
<button type="submit" disabled={!draftTitle.trim()}>
Save
</button>
</div>
</form>
</div>
</div>
);
}
// Styling definitions
const headerStyle = {
backgroundColor: "#f4f4f4",
padding: 8,
fontWeight: "bold",
textAlign: "center",
};
const timeLabelStyle = {
backgroundColor: "#fafafa",
padding: 4,
fontSize: 12,
textAlign: "right",
};
const cellStyle = {
backgroundColor: "#fff",
minHeight: 48,
border: "none",
padding: 2,
textAlign: "left",
verticalAlign: "top",
cursor: "pointer",
};
const eventChipStyle = {
backgroundColor: "#0070f3",
color: "#fff",
fontSize: 11,
borderRadius: 3,
padding: "2px 4px",
marginBottom: 2,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
};
const overlayStyle = {
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: "rgba(0,0,0,0.4)",
display: "flex",
alignItems: "center",
justifyContent: "center",
};
const modalStyle = {
backgroundColor: "#fff",
padding: 20,
borderRadius: 6,
minWidth: 300,
};
Complexity & Performance Analysis
- Lookup Construction Time: $O(E)$ where $E$ is the total count of created events. Executed only when
eventsstate changes. - Render Time: $O(N + E)$ where $N = 7 \times 24 = 168$ grid cells. Render iterates over cells once, performing an $O(1)$ lookup for each.
- Space Complexity: $O(E)$ to store events and key references in the indexed map.
Production Edge Cases & Extensions
- Overlapping Events: Storing an array per cell key naturally accommodates multiple events in the same time block without structural breakage.
- Keyboard Accessibility: Using interactive HTML elements (
<button>) for cells provides native keyboard tab-focus and activation out of the box. Addingrole="dialog"andaria-modal="true"ensures screen readers handle the modal appropriately. - Data Model Scalability: In a real calendar application,
dayandhourattributes would be stored as absolute ISO dates (e.g.,2024-10-15T09:00:00Z). Cells would extract display indices relative to the selected week view anchor date.