Frequency Queries

  • + 2 comments

    I was experiencing the same issue. It turns out that the boilerplate code is the problem, because if you set freqQuery(queries: [[Int]])->[Int] to simply return [], it still fails some of the tests with timeout.

    So, in the boilerplate, I replaced:

    let queries: [[Int]] = AnyIterator{ readLine()?.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) }.prefix(q).map {
        let queriesRow: [Int] = $0.split(separator: " ").map {
            if let queriesItem = Int($0) {
                return queriesItem
            } else { fatalError("Bad input") }
        }
    
        guard queriesRow.count == 2 else { fatalError("Bad input") }
    
        return queriesRow
    }
    

    with:

    var queries = [[Int]]()
    while let raw = readLine() {
        guard raw.count >= 3, raw[raw.index(raw.startIndex, offsetBy: 1)] == " " else { fatalError("Bad input") }
        guard let op = Int("\(raw[raw.startIndex])"),
            let val = Int("\(raw[raw.index(raw.startIndex, offsetBy: 2)..<raw.endIndex])")
        else {
            fatalError("Bad input")
        }
        queries.append([op, val])
    }
    

    And then all my tests passed. I'll submit this as a suggestion for them to fix as well. Cheers!