# Linear time solution but Time Limit Exceeded

#1

Hello, I solved the problem for the linear time. May be it doesn’t look beautiful, but it works for O(A+B+C) time. But the solution hasn’t passed:

Time Limit Exceeded. Your submission didn’t complete in the allocated time limit.

Could anyone please tell me, whats wrong?

``````class Solution {
func solve(_ A: inout [Int], _ B: inout [Int], _ C: inout [Int]) -> Int {
var i = 0
var j = 0
var k = 0

let aCount = A.count
let bCount = B.count
let cCount = C.count

var minRes = Int.max

while true {

let maxFromTriplet = max(max(A[i], B[j]), C[k])
let minFromTriplet = min(min(A[i], B[j]), C[k])

let res = maxFromTriplet-minFromTriplet
minRes = min(res, minRes)

if minRes == 0 {
return 0
}

if A[i] < maxFromTriplet {
if i != aCount-1 { i += 1 }
}

if B[j] < maxFromTriplet {
if j != bCount-1 { j += 1 }
}

if C[k] < maxFromTriplet {
if k != cCount-1 { k += 1 }
}

if i == aCount-1 && j == bCount-1 && k == cCount-1 {
let maxFromTriplet = [A[i], B[j], C[k]].max()!
let minFromTriplet = [A[i], B[j], C[k]].min()!

let res = abs(maxFromTriplet-minFromTriplet)
minRes = min(res, minRes)
break
}

}

return minRes
}``````

#2
``````if i == aCount-1 && j == bCount-1 && k == cCount-1
``````

Actually you can stop when either one of the three pointers hits the end of the corresponding array. When this happens, it is no longer possible to improve the minimum difference.

#3

look out for this test case
1 6
1 3
2 4 5