algoadvance

Leetcode 551. Student Attendance Record I

Problem Statement

You are given a string s representing an attendance record for a student. The record only contains the following three characters:

A student could be rewarded if their attendance record doesn’t contain:

You need to implement a function checkRecord(String s) that returns true if the student could be rewarded according to the given criteria, or false otherwise.

Example 1:

Input: s = "PPALLP"
Output: true

Example 2:

Input: s = "PPALLL"
Output: false

Clarifying Questions

  1. Question: Can the input string be empty?
    • Answer: In this problem context, it is safe to assume the input string is not empty as it represents the attendance record.
  2. Question: What is the maximum length of the string?
    • Answer: The problem doesn’t explicitly state a maximum length, but typically for interview questions, constraints are reasonable. Let’s assume it fits well within modern memory limits (e.g., up to 10^4 characters).
  3. Question: Are there any invalid characters in the input string?
    • Answer: The problem specifies that the input string will only contain ‘A’, ‘L’, and ‘P’, so we can assume there are no invalid characters.

Strategy

  1. Count ‘A’ characters: Traverse the string and count occurrences of ‘A’. If more than one ‘A’ is found, return false.

  2. Check for continuous ‘L’ characters: While traversing, check for sequences of three or more consecutive ‘L’ characters. If such a sequence is found, return false.

  3. Return true: If traversal completes without violating any rules, return true.

Code

public class Solution {

    public boolean checkRecord(String s) {
        int absents = 0;
        int consecutiveLates = 0;

        for (char c : s.toCharArray()) {
            if (c == 'A') {
                absents++;
                if (absents > 1) {
                    return false; // More than one 'A'
                }
            }

            if (c == 'L') {
                consecutiveLates++;
                if (consecutiveLates > 2) {
                    return false; // More than two continuous 'L'
                }
            } else {
                consecutiveLates = 0; // Reset count if the current character is not 'L'
            }
        }
        
        return true;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // Test cases
        System.out.println(solution.checkRecord("PPALLP")); // should return true
        System.out.println(solution.checkRecord("PPALLL")); // should return false
    }
}

Time Complexity

By following these steps, we ensure the solution is both efficient and adheres to the problem’s constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI