O(n) Swift approach results in TLE


  • 0
    K

    I've implemented the following solution and submitted it for review, however I get a TLE error. I believe that this should not be the case considering the O(n) time complexity and others' similar solutions.

    Anyone else have the same problem with Swift? This is not the first time I've encountered this issue using Swift on Leetcode problems.

    func convert(_ s: String, _ numRows: Int) -> String {
        let count = s.characters.count
        var strings: [String] = Array(repeating: "", count: numRows)
        var i: Int = 0
        while i < count {
            for idx in 0..<numRows {
                guard i < count else { break }
                strings[idx] += String(s[s.index(s.startIndex, offsetBy: i)])
                i += 1
            }
            guard numRows > 2 else { continue }
            for idx in (1...numRows - 2).reversed() {
                guard i < count else { break }
                strings[idx] += String(s[s.index(s.startIndex, offsetBy: i)])
                i += 1
            }
        }
        for idx in 1 ..< numRows {
            strings[0] += strings[idx]
        }
        return strings[0]
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.