LeetCode in Swift: Search Insert Position

Problem Statement

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 2 [1,3,5,6], 2 1 [1,3,5,6], 7 4 [1,3,5,6], 0 0

Original LeetCode problem page

My Solution in Swift

I employed a binary search to find a given target value in a given sorted array. This results in an O(log n) solution.

Try It Yourself

1: each links to a blog post of mine that is dedicated to the problem
2: total execution time of a solution on my MacBook Pro (Late 2013, 2.6 GHz Intel Core i7, 16 GB 1600 MHz DDR3). Each solution is compiled with following command:

$ swiftc -O -sdk `xcrun --show-sdk-path --sdk macosx` json.swift main.swift -o mySolution

The total execution time is the average of 10 runs.
3: these test cases are semi-automatically :P retrieved from LeetCode Online Judge system and are kept in JSON format
4: each Xcode project includes everything (my Swift solution to a problem, its JSON test cases and a driver code to test the solution on those test cases)

Problem1Time2Test Cases3My Xcode Project4
Search Insert Position0.002ms Save  (1696) Save  (1644)

More Problems Solved in Swift

My full list of LeetCode problems attempted using Swift