Start learning free

LESSON 246 OF 293 · HELPER FUNCTIONS

Letter Grades in Rust: A Helper and a Loop

Practice Read the full explanation

Given an array of integers scores, return the letter grade of every score, in the same order as the scores.

Each score gets one letter:

  • 90 to 100: "A"
  • 80 to 89: "B"
  • 70 to 79: "C"
  • 60 to 69: "D"
  • 0 to 59: "F"

The work is split between two functions. The first one is a helper: it gets one score and returns its letter. The second one, the function that is graded, goes over the scores and collects the helper's letter for each of them.

 

Example 1:

Input: scores = [95, 82, 71]
Output: ["A", "B", "C"]
Explanation: 95 is in the A range (90 to 100), 82 is in the B range and 71 is in the C range.

Example 2:

Input: scores = [65, 40]
Output: ["D", "F"]
Explanation: 65 is between 60 and 69, so it gets a D. 40 is below 60, so it gets an F.

Example 3:

Input: scores = [100, 90, 89]
Output: ["A", "A", "B"]
Explanation: 100 and 90 are both in the A range: 90 is its lowest score. 89 is one point short of it, so it gets a B.

 

Constraints:

  • scores has at least one score.
  • Every score is an integer from 0 to 100.
  • The result has one letter per score, in the same order as scores.
STEP 1 OF 9
    Ctrl + Enter to check

    RUST · HELPER FUNCTIONS

    Letter Grades in Rust, explained

    Problem overview

    Given a vector of scores, letter_grades returns a vector of letters, one per score and in the same order. The ranges are 90 to 100 for "A", 80 to 89 for "B", 70 to 79 for "C", 60 to 69 for "D", and 0 to 59 for "F". The work is split in two: the helper letter_grade turns one score into its letter, and letter_grades applies it to every score. For [95, 82, 71] the result is ["A", "B", "C"], and for [100, 90, 89] it is ["A", "A", "B"]: 90 is the lowest A, and 89 is one point short of it.

    Approach: check from the top, one range at a time

    The helper tests the highest range first. Because return ends the function, every later check only runs for scores that failed the earlier ones. After the test for 90, a later score >= 80 can only be true for 80 to 89, so each condition needs just one bound. Checking from the bottom would need an upper bound on every test as well.

    The second function is a plain collecting loop: start with an empty vector, push one letter for each score, and return the vector after the loop.

    Step by step

    1. Test for A. If score is at least 90, return "A".to_string().
    2. Test for B, C and D. Three more if statements, for 80, 70 and 60, in that order.
    3. Fall through to F. If no test matched, the score is below 60, so the last line returns "F" with no condition.
    4. Start the result. In letter_grades, let mut grades = Vec::new(); makes an empty vector. It is mut because letters are pushed into it, and Rust infers its element type from the first push.
    5. Loop over &scores. The loop runs once per score, so each score gives one letter.
    6. Push the helper's answer. Self::letter_grade(*score) returns the letter, and grades.push(...) adds it at the end, which keeps the original order.
    7. Return after the loop. A return inside the loop would hand back after the first score.

    The solution in Rust

    impl Solution {
        fn letter_grade(score: i32) -> String {
            if score >= 90 {
                return "A".to_string();
            }
            if score >= 80 {
                return "B".to_string();
            }
            if score >= 70 {
                return "C".to_string();
            }
            if score >= 60 {
                return "D".to_string();
            }
            return "F".to_string();
        }
    
        fn letter_grades(scores: Vec<i32>) -> Vec<String> {
            let mut grades = Vec::new();
            for score in &scores {
                grades.push(Self::letter_grade(*score));
            }
            return grades;
        }
    }
    

    Rust details worth knowing:

    • &str against String. A literal such as "A" is a &str, a borrowed piece of text. The helper's return type is String, an owned, growable string, and Rust does not convert one into the other on its own. return "A"; fails with expected `String`, found `&str`, and .to_string() is the fix.
    • *score. Looping over &scores gives score as a &i32. The helper takes an i32, so the call passes *score, the number behind the reference.
    • Separate variables. The helper's parameter is also called score, but it is a different variable from the loop's. Each function has its own.
    • Self::. Calling another function of the same impl that takes no self needs Self:: before its name.

    Following two scores through the helper

    Take 82. It is not at least 90, so the first if is skipped. It is at least 80, so the second one returns "B" and the later tests never run. Now take 40. It fails the tests for 90, 80, 70 and 60 one after another, and reaches the last line, which returns "F". Every score ends at exactly one return, so the helper always produces exactly one letter. That is also why the function compiles without an else anywhere: the final return covers whatever the earlier tests did not catch.

    Why split the work in two

    The helper knows about one score and nothing about vectors, and the loop knows about vectors and nothing about grade boundaries. If the cut-offs changed, only letter_grade would need an edit. If the input became a different collection, only the loop would. Each function can also be tried on its own: letter_grade(89) returns "B" and letter_grade(90) returns "A", which is a quick way to check the boundaries before running the whole vector through.

    The loop itself never decides anything about grades. It forwards each score to the helper and stores whatever comes back, so the output always has exactly as many letters as the input has scores.

    Edge cases and common mistakes

    • Boundaries. The scores 59, 60, 69, 70, 79, 80, 89 and 90 sit right at the edges. Using > instead of >= would turn 90 into a B.
    • Order of the tests. If the test for 60 came first, every passing score would be a D. The checks must run from the highest range down.
    • Returning inside the loop. Only the first letter would come back, and the function would not match the vector it should return.
    • Lowest and highest scores. 0 falls through to "F", and 100 is covered by score >= 90.

    Testing

    • [95, 82, 71] gives ["A", "B", "C"].
    • [65, 40] gives ["D", "F"].
    • [100, 90, 89] gives ["A", "A", "B"].
    • [0, 59, 60, 69, 70, 79, 80, 89] gives ["F", "F", "D", "D", "C", "C", "B", "B"].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free