Skip to content
Problem 551 · LeetCode 551(opens in a new tab)

Student Attendance Record I

EasyStrings

A student's attendance is written as a string s, one letter per school day: A means absent, L means late and P means present.

The student earns an award when two things hold: they were absent on at most one day in total, and they were never late on three or more days in a row. Return true if the student earns the award, and false if not.

Example 1

Input:  s = "LPALLP"
Output: true
Why:    one absence, and the longest run of L is 2
2 more examples and the constraints

Example 2

Input:  s = "APLLLP"
Output: false
Why:    days 2, 3 and 4 are late in a row

Example 3

Input:  s = "PAPA"
Output: false
Why:    two absences, even though they are far apart

Constraints

  • 1 ≤ length of s ≤ 1,000
  • Every letter of s is A, L or P

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count and searchO(n)
  2. One pass with two countersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 lettersVerdict
Count and searchO(n)
Short; reads the string twice
One pass with two countersO(n)
Best; one pass, stops early

n = length of the record.

Edge cases to test

  • Two absences far apart. "PAPA" fails: the absence rule counts the whole record, not a run.
  • Late days split by an absence. "LLALL" passes: no three late days are next to each other.
  • Run at the very end. "PPLLL" fails on the last letter; check after every letter, not only on a reset.
  • One letter. "A", "L" and "P" all pass.

Common mistakes

  • Counting all late days instead of the current run, so "LLPLL" wrongly fails.
  • Failing on one absence: the rule is fewer than 2, so one is allowed.
  • Only checking the run length when a non-L letter arrives, so a run at the end is missed.

How to talk through it

  1. 1Clarify. Is one absence allowed? Does an A also break a late run? Only A, L and P appear?
  2. 2Give the simple answer. Count A and look for the substring LLL. It is O(n) already.
  3. 3Tighten it. One pass with two counters lets you stop on the first rule broken.
  4. 4Code the pass. Reset the late run on any letter that is not L; check both limits after each letter.
  5. 5Test out loud. Run "LLALL", "PAPA" and a run of three L at the very end.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?