Student Attendance Record I — Easy Problem & Solution

An attendance record is a string where each character is 'A' (absent), 'L' (late) or 'P' (present).

  • Difficulty: Easy
  • Topics: Strings
  • Asked at: TCS, Infosys, Cognizant
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

An attendance record is a string where each character is 'A' (absent), 'L' (late) or 'P' (present).

A student is eligible for an award when they were absent fewer than 2 days in total and were never late on 3 or more consecutive days.

Return true if the record earns an award.

Example 1

Input: s = "PPALLP"
Output: true
Explanation: One absence and never three L's in a row.

Example 2

Input: s = "PPALLL"
Output: false
Explanation: Three consecutive late days.

Example 3

Input: s = "AA"
Output: false
Explanation: Two absences.

Constraints

  • 1 <= s.length <= 1000
  • s[i] is 'A', 'L' or 'P'.

How to solve Student Attendance Record I

Both rules are decidable in one pass: absences are a running total, and 'three in a row' only ever needs the current character and the two before it.

Approach

  1. Sweep the string keeping absent, the number of 'A' seen.
  2. At each 'L', check whether the two preceding characters are also 'L'; if so, return false immediately.
  3. After the sweep, return absent < 2.

Why it works

A run of three or more late days necessarily contains a position whose two predecessors are both 'L', so the look-back catches every violation. The absence rule is a plain total and needs no context at all.

Complexity

  • Time — O(n)
  • Space — O(1)

Pitfalls

  • absent <= 2 is wrong — two absences already disqualify.
  • Resetting a late streak on 'A' but not on 'P' (or the other way round) — any non-'L' breaks the run.

Reference solution

Python

def checkRecord(s: str) -> bool:
    absent = 0
    for i, c in enumerate(s):
        if c == "A":
            absent += 1
        if c == "L" and i >= 2 and s[i - 1] == "L" and s[i - 2] == "L":
            return False
    return absent < 2

JavaScript

var checkRecord = function(s) {
    var absent = 0;
    for (var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (c === "A") absent++;
        if (c === "L" && i >= 2 && s.charAt(i - 1) === "L" && s.charAt(i - 2) === "L") return false;
    }
    return absent < 2;
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 282 strings problems · the whole catalogue