The Full Counting Sort

  • + 2 comments

    Swift: No spoilers of the solution here, I just give some tips on how to optimise reading the input in Swift.

    Reading input and general string manipulation in Swift can be pretty slow if you use the standard/normal techniques. You may struggle with Test Case #4 and almost certainly will time out on #5.

    So, for Test Case #5...

    I tried various experiments and reading the input alone takes 0.48s with this code:

    let size = Int(readLine()!)!
    for i in 0 ..< size {
        let line = readLine()!
    }
    

    Adding in the standard "Foundation" way to process this into an Int and a String, like this:

    let size = Int(readLine()!)!
    for i in 0 ..< size {
        let line = readLine()!
        let comps = line.components(separatedBy: " ")
        let x = Int(comps[0])!
        let str = comps[1]
    }
    

    ...with no other code times out (>2s at time of writing). So unfortunately just getting the input is too slow using this technique. Another way to process the line string into an Int and String is this:

    let (x, str) = line.withCString {
        (cStr: UnsafePointer<Int8>) -> (Int, String) in
        let x = Int(atoi(cStr))
        let pSpc = strchr(cStr, 0x20)!
        let str = String(validatingUTF8: pSpc + 1)!
        return (x, str)
    }
    

    ...and this now takes 1.09s.

    This should be enough for you to solve the rest by yourself, but I will just point out that it took 1.41s to read the input plus the processing for the algorithm alone (no output) using the above code. My final solution took just 1.16s because I optimised away unnecessary code from the withCString closure above as well. Without that optimisation you will be sailing pretty close to the 2s time-out.