We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Student Attendance Record I

Number: 551

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given a string s representing a student's attendance record, determine if the student is eligible for an award. Eligibility requires that the student has been absent strictly fewer than 2 times (i.e., <2 'A's) and has never been late for 3 or more consecutive days (i.e., no occurrence of "LLL"). Return true if the student meets both criteria, or false otherwise.


Key Insights

  • Count the number of 'A' (Absent) characters in the string. The count must be less than 2.
  • Check for consecutive occurrences of 'L' (Late) characters. There should not be any sequence of 3 or more consecutive 'L's.
  • A single traversal of the string is sufficient to verify both conditions.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), using just a few counters regardless of the input size.


Solution

The solution involves iterating through the input string exactly once. During the iteration, two pieces of information are tracked:

  1. A counter for the total number of absences ('A').
  2. A counter for consecutive tardies ('L').

For each character:

  • If it is an 'A', increment the absence counter. If the counter reaches 2, we can immediately return false.
  • If it is an 'L', increment the consecutive late counter. If the consecutive counter reaches 3, return false immediately.
  • If the character is 'P' (Present) or any character other than 'L', reset the consecutive late counter to 0.

If the loop completes without triggering either disqualification condition, return true.


Code Solutions

# Define a function to check student attendance eligibility.
def checkRecord(s):
    absences = 0  # Counter for absent days.
    consecutive_late = 0  # Counter for consecutive late days.
    
    # Iterate through each character in the attendance record.
    for char in s:
        if char == 'A':
            absences += 1  # Increment absence counter.
            if absences >= 2:
                return False  # Too many absences.
        if char == 'L':
            consecutive_late += 1  # Increment late counter.
            if consecutive_late >= 3:
                return False  # Three consecutive lates found.
        else:
            # Reset consecutive late counter if character is not 'L'.
            if char != 'L':
                consecutive_late = 0
                
    return True  # Passed all conditions.

# Example usage:
print(checkRecord("PPALLP"))  # Output: True
print(checkRecord("PPALLL"))  # Output: False
← Back to All Questions