PROBLEM STATEMENT
This problem is from Leetcode Student Attendance Record
. Problem statement in short is given below:
Given a record string with
'A' (absent),
'L' (late), and
'P' (present),
return true if there are fewer than 2 absences and no 3+ consecutive lates; else false.
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:
PERFORMANCE ANALYSIS
RUNTIME | 1 ms | Beats 35.73 % |
MEMORY | 41.90 MB | Beats 9.31 % |