Created
October 24, 2018 21:28
-
-
Save huntermonk/6789266af2779ebcb9d34e8d7173065b to your computer and use it in GitHub Desktop.
Potential answer for Rotation Point question in Interview Cake.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func findRotationPoint(in words: [String]) -> Int { | |
let firstWord = words[0] | |
var floorIndex = 0 | |
var ceilingIndex = words.count - 1 | |
while floorIndex < ceilingIndex { | |
// guess a point halfway between floor and ceiling | |
let guessIndex = floorIndex + ((ceilingIndex - floorIndex) / 2) | |
// if guess comes after first word or is the first word | |
if words[guessIndex] >= firstWord { | |
// go right | |
floorIndex = guessIndex | |
} else { | |
// go left | |
ceilingIndex = guessIndex | |
} | |
// if floor and ceiling have converged | |
if (floorIndex + 1) == ceilingIndex { | |
// between floor and ceiling is where we flipped to the beginning | |
// so ceiling is alphabetically first | |
break | |
} | |
} | |
return ceilingIndex | |
} | |
// returns 2 | |
findRotationPoint(in: ["a", "b", "c"]) | |
func rotationPoint<T: Comparable>(from array: [T]) -> Int? { | |
guard let first = array.first else { | |
return nil | |
} | |
var leftIndex = 0 | |
var rightIndex = array.count - 1 | |
while leftIndex + 1 < rightIndex { | |
let distance = rightIndex - leftIndex | |
let middleIndex = (distance / 2) + leftIndex | |
let middleValue = array[middleIndex] | |
if middleValue == first || middleValue < array[middleIndex - 1] { | |
// Found the rotation point. | |
return middleIndex | |
} | |
if middleValue < first { | |
// Rotation point is to left. | |
rightIndex = middleIndex | |
} else if middleValue > first { | |
// Rotation point is to the right. | |
leftIndex = middleIndex | |
} | |
} | |
// This is optional. You could also say there is no rotation point, | |
// and return `nil`. | |
if leftIndex + 1 == rightIndex { | |
// This array is in order. The rotation point is at the beginning. | |
return 0 | |
} | |
return nil | |
} | |
// returns Optional(0) | |
rotationPoint(from: ["a", "b", "c"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment