Start learning free

LESSON 243 OF 291 · HELPER FUNCTIONS

Letter Grades in Scala: Helper Method and ArrayBuffer

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

    SCALA · HELPER FUNCTIONS

    Letter Grades in Scala, explained

    Problem overview

    Given an array of integer scores, letterGrades returns the letter for each score, 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 letterGrade turns one score into a letter, and letterGrades calls it for every score and collects the results. For [95, 82, 71] the result is ArrayBuffer(A, B, C). For [100, 90, 89] it is ArrayBuffer(A, A, B): 90 is the lowest A, and 89 is one point short.

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

    The helper checks the highest range first. If the score is at least 90, it returns "A" and stops. Any code after that only sees scores below 90, so the next test can say just "at least 80" instead of "from 80 to 89". Each test can rely on the ones before it. Whatever survives all four tests is below 60 and gets "F" with no test of its own.

    The second method is a plain collect loop: one letter per score, appended to a buffer that grows.

    Tracing one score

    Take a score of 82. The test score >= 90 is false, so the method moves on. The test score >= 80 is true, so it returns "B" and never looks at the 70 and 60 tests. Take 59: all four tests are false, so the method reaches the last line and returns "F". The helper always returns exactly once, so every score gets exactly one letter.

    Why a helper

    The loop in letterGrades doesn't need to know where the grade boundaries are. If the school changed the A boundary to 93, only letterGrade would change. Giving each method one job also makes each easy to test on its own: call letterGrade(90) and check for "A" without building any array.

    Step by step

    1. Test for an A. In letterGrade, if score >= 90, return "A".
    2. Test for a B, a C and a D the same way, with 80, 70 and 60. Because higher scores already returned, each test covers exactly one range.
    3. Return "F" after the last if.
    4. In letterGrades, create an empty ArrayBuffer[String] named grades in a val.
    5. Loop over the scores with for (score <- scores).
    6. Append the helper's answer with grades += letterGrade(score).
    7. Return grades after the loop, so every score has been handled first.

    The solution in Scala

    class Solution {
        def letterGrade(score: Int): String = {
            if (score >= 90) {
                return "A"
            }
            if (score >= 80) {
                return "B"
            }
            if (score >= 70) {
                return "C"
            }
            if (score >= 60) {
                return "D"
            }
            return "F"
        }
    
        def letterGrades(scores: Array[Int]): ArrayBuffer[String] = {
            val grades = ArrayBuffer[String]()
            for (score <- scores) {
                grades += letterGrade(score)
            }
            return grades
        }
    }
    

    Scala details worth knowing:

    • ArrayBuffer is growable. An Array has a fixed size, but an ArrayBuffer from scala.collection.mutable can grow with +=. The lesson's code already has ArrayBuffer imported; in a file of your own, add import scala.collection.mutable.ArrayBuffer.
    • val does not freeze the buffer. It only means grades always refers to the same buffer. The contents can still change.
    • Printing. An ArrayBuffer prints as ArrayBuffer(A, B, C), without quotes around the strings.
    • Calling the helper. Both methods belong to Solution, so letterGrade(score) needs no object in front of it.

    A shorter form

    Scala collections have a map method that applies a function to every element and returns the results. The body of letterGrades can be one line, ArrayBuffer.from(scores.map(letterGrade)): map produces an array of letters and ArrayBuffer.from copies it into a buffer. For [95, 82, 71] it gives ArrayBuffer(A, B, C), the same as the loop. The lesson uses the explicit loop first because it shows each piece: the empty buffer, the visit to each score and the append. Once that loop is clear, map is the same idea in one line.

    Edge cases and common mistakes

    • Boundaries. 90, 80, 70 and 60 belong to the higher letter, which is why the tests use >=. With >, a 90 would become a B. The scores 0, 59, 60, 79, 80, 69 and 70 give F, F, D, C, B, D, C.
    • Checking the lowest range first. A test for "at least 60" placed first would return "D" for every passing score, even 95.
    • Returning inside the loop. The method would end after the first score, so only one letter would be handled instead of the whole list.
    • Chaining else if instead. The same logic can be written as one if / else if / else chain. The separate if statements with return are equivalent, because a returning branch never falls through to the next test. Mixing the two styles, such as an if with return followed by an else that is never needed, only adds clutter.
    • Scores out of range. The lesson guarantees scores from 0 to 100. A score of 150 would still get "A" and a score of -5 would get "F", because the helper only compares against the lower bounds. Real code would validate its input first.
    • Order. Appending in loop order keeps the letters in the order of the scores.

    Testing

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