Maximum Students Taking Exam - Problem

Given an m × n matrix seats that represents seat distributions in a classroom. If a seat is broken, it is denoted by '#' character, otherwise it is denoted by '.' character.

Students can see the answers of those sitting next to them on the left, right, upper left and upper right, but they cannot see the answers of students sitting directly in front or behind them.

Return the maximum number of students that can take the exam together without any cheating being possible.

Note: Students must be placed in seats that are in good condition (marked with '.').

Input & Output

Example 1 — Basic Case
$ Input: seats = [[".","#"],["#","#"],["#","."],["#","#"],[".","#"]]
Output: 1
💡 Note: Only one student can be placed at seats[0][0] or seats[2][1] or seats[4][0] without any cheating possibility
Example 2 — Multiple Students
$ Input: seats = [[".",".","."],[".",".","."],[".",".","."]]
Output: 4
💡 Note: Students can be placed at (0,0), (0,2), (2,0), (2,2) in a checkerboard pattern to avoid cheating
Example 3 — All Broken Seats
$ Input: seats = [["#","#"],["#","#"]]
Output: 0
💡 Note: No students can be placed since all seats are broken

Constraints

  • 1 ≤ seats.length ≤ 8
  • 1 ≤ seats[r].length ≤ 8
  • seats[r][c] is either '.' or '#'

Visualization

Tap to expand
Maximum Students Taking Exam INPUT Classroom Seats (m x n matrix) . # row 0 # # row 1 # . row 2 # # row 3 . # row 4 = Good seat (.) = Broken (#) Can see: Left, Right, Upper-Left, Upper-Right Cannot see: Front, Back ALGORITHM STEPS 1 Bitmask DP Setup Each row state = bitmask of student positions 2 Valid State Check No adjacent students in same row (left/right) 3 Row Transition Check diagonal conflicts with previous row 4 Find Maximum DP tracks max students for each valid state State Analysis Row 0: 1 seat Row 1: 0 seats Row 2: 1 seat FINAL RESULT Optimal Student Placement S # # # # . # # . # OUTPUT 1 Only 1 student can be placed without cheating risk Key Insight: Bitmask DP efficiently handles exponential state space. Each row's valid seating arrangements are represented as bitmasks. Transitions between rows check diagonal conflicts (upper-left, upper-right) to ensure no cheating. Time: O(m * 4^n), Space: O(2^n) where m=rows, n=cols. TutorialsPoint - Maximum Students Taking Exam | Bitmask DP Approach
Asked in
Google 15 Facebook 12 Microsoft 8
23.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen