Student Attendance Record I
Problem
Given an attendance string of 'A' (absent), 'L' (late), 'P' (present), the student is rewardable if they have strictly fewer than 2 absences total and were never late 3 or more days in a row.
s = "PPALLP"truedef check_record(s):
absences = 0
late_streak = 0
for ch in s:
if ch == 'A':
absences += 1
late_streak = 0
elif ch == 'L':
late_streak += 1
if late_streak >= 3:
return False
else:
late_streak = 0
if absences >= 2:
return False
return True
function checkRecord(s) {
let absences = 0, lateStreak = 0;
for (const ch of s) {
if (ch === 'A') { absences++; lateStreak = 0; }
else if (ch === 'L') {
lateStreak++;
if (lateStreak >= 3) return false;
} else lateStreak = 0;
if (absences >= 2) return false;
}
return true;
}
class Solution {
public boolean checkRecord(String s) {
int absences = 0, lateStreak = 0;
for (char ch : s.toCharArray()) {
if (ch == 'A') { absences++; lateStreak = 0; }
else if (ch == 'L') {
lateStreak++;
if (lateStreak >= 3) return false;
} else lateStreak = 0;
if (absences >= 2) return false;
}
return true;
}
}
bool checkRecord(string s) {
int absences = 0, lateStreak = 0;
for (char ch : s) {
if (ch == 'A') { absences++; lateStreak = 0; }
else if (ch == 'L') {
lateStreak++;
if (lateStreak >= 3) return false;
} else lateStreak = 0;
if (absences >= 2) return false;
}
return true;
}
Explanation
The student is rewardable under two simple rules: fewer than 2 absences total, and never 3 lates in a row. We can verify both in a single left-to-right pass while keeping just two small counters.
We track absences (a running total) and late_streak (how many 'L' we have seen back-to-back). For each character we update these: an 'A' bumps absences and resets the late streak, an 'L' grows the streak, and a 'P' just resets the streak to zero.
The two failure checks happen as we go. If late_streak reaches 3 we return false immediately, and if absences reaches 2 we also bail out. Resetting the streak whenever the character is not 'L' is what makes it count consecutive lates rather than total lates.
If we finish the whole string without tripping either check, the student is rewardable and we return true.
Example: "PPALLP". We see two P's, then one A (absences = 1), then two L's in a row (late_streak = 2, never hits 3), then a P resets the streak. No rule is broken, so the answer is true.