Problem Statement
You are given a string s
representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters:
'A'
: Absent.'L'
: Late.'P'
: Present.
The student is eligible for an attendance award if they meet both of the following criteria:
- The student was absent (
'A'
) for strictly fewer than 2 days total. - The student was never late (
'L'
) for 3 or more consecutive days.
Return true
if the student is eligible for an attendance award, or false
otherwise.
Solution
We can solve this problem in one pass. In a for loop keep track of both conditions and check at the end of the loop. See the code sample below:
public boolean checkRecord(String s) {
Boolean isAward = false;
Boolean neverLate = true;
int count = 0;
for(int i=0; i<s.length(); i++) {
// check for first condition
if(s.charAt(i) == 'A') {
count = count+1;
}
// check for second condition
if(s.charAt(i) == 'L' && i < (s.length()-2) ) {
if((s.charAt(i+1) == 'L' && (s.charAt(i+2) == 'L'))) {
neverLate = false;
}
}
} // endFor
// check if both conditions satisfy
if(count < 2 && neverLate == true) {
isAward = true;
}
return isAward;
}
You can checkout the code from Github here: Student Attendance Record – First Approach. See the performance of this approach below: