Facebook | Phone Screen | Locker Room

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2019-06-26Added By Anonymous
Source: Link

Company: Facebook
Role: e3, e4
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

It is the end of the school year, and the graduating class of Moore Science High (n students in all) has decided to end the year by making quite a lot of noise. They line up in the locker room, where all n lockers are closed. The first student runs down the row of lockers, opening each one. Then, the second runs down, slamming every other locker (this is where the noise comes in).

The third student then runs down, opening (or slamming) every third locker, and so on until all n students have gone through, each opening (or closing) each locker evenly divisible by i, where i is the ith student. Write a function that prints each locker state after each student is done.

Output:
["O", "O", "O", "O"]
["O", "C", "O", "C"]
["O", "C", "C", "C"]
["O", "C", "C", "O"]

func lockerMusic(_ n: Int){
  var str = [String](repeating: "C", count: n)
      for i in 1...n{
          for j in 1...n where j%i == 0 {
              if str[j-1] == "O"{
                  str[j-1] = "C"
              }else{
                  str[j-1] = "O"
              }
          }
          print(str)
      }
    }
    lockerMusic(4)

Comments