#551
Student Attendance Record I
EasyStringArrayString
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can achieve the same result with a single pass through the string while keeping track of absences and consecutive lates. This is efficient and straightforward.
⚙️
Algorithm
6 steps- 1Step 1: Initialize counters for absences and consecutive lates.
- 2Step 2: Loop through each character in the string.
- 3Step 3: Increment the absence counter for 'A' and check if it exceeds 1.
- 4Step 4: Increment the late counter for 'L' and check if it reaches 3.
- 5Step 5: Reset the late counter if the character is 'P'.
- 6Step 6: Return true if no conditions for disqualification are met.
solution.py15 lines
1def checkRecord(s):
2 absences = 0
3 late_count = 0
4 for char in s:
5 if char == 'A':
6 absences += 1
7 if absences > 1:
8 return False
9 if char == 'L':
10 late_count += 1
11 if late_count == 3:
12 return False
13 else:
14 late_count = 0
15 return Trueℹ
Complexity note: The time complexity is O(n) because we only traverse the string once. The space complexity is O(1) since we are using a constant amount of space for counters.
- 1Count occurrences efficiently in a single pass.
- 2Use simple counters to track conditions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.