Commented Swift solution with O(1) memory and O(n) runtime

  • 0

    There's no Swift submission option, but I wanted to see try this in Swift, so here it is:

    import Foundation
    class Solution {
        let nums: [Int]
        let numSize: Int
        init(_ nums: [Int], _ numSize: Int) {
            self.nums = nums
            self.numSize = numSize
        func pick(_ target: Int) -> Int {
            // want to upper bound at O(n)
            // return first of iteration or
            // random index match
            // this guarantees we won't have infinite
            // execution
            for i in 0..<numSize {
                // unruly but unavoidable random syntax
                let idx = Int(arc4random_uniform((UInt32)(numSize - i))) + i
                if nums[idx] == target {
                    return idx
                if nums[i] == target {
                    return i
            return 0


    print(Solution([1,2,3,3,3], 5).pick(3))

Log in to reply

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