-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotationPointBinaryTree.js
More file actions
44 lines (36 loc) · 969 Bytes
/
RotationPointBinaryTree.js
File metadata and controls
44 lines (36 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Find the starting index of an array of sorted words.
// Use a Binary Tree implementation
// Constraints: O(log(n))
const expect = require('expect');
function rotationPoint(words) {
const first = words[0];
let floor = 0;
let ceiling = words.length - 1;
while (floor < ceiling) {
const mid = Math.round((ceiling - floor) / 2) + floor;
if (words[mid].localeCompare(first) > 0) {
floor = mid;
}
else {
ceiling = mid;
}
if (floor + 1 === ceiling) {
// converged and last element is not the start
if (words[ceiling].localeCompare(first) > 0) {
return 0;
}
return ceiling;
}
}
}
// Test
const testFunction = () => {
expect(
rotationPoint(['dog', 'hippomoztimus', 'mammoth', 'parrot', 'zebra', 'ant', 'cat'])
).toEqual(5);
expect(
rotationPoint(['apple', 'banana', 'mango', 'pineapple', 'watermelon'])
).toEqual(0);
};
testFunction();
console.log('All tests passed');