Skip to content

34. Find First and Last Position of Element in Sorted Array #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions solutions/findFirstAndLastPositionOfElementInSortedArray.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import searchRange from "./findFirstAndLastPositionOfElementInSortedArray";

const TEST_CASES = new Map<[number[], number], [number, number]>([
[[[5, 7, 7, 8, 8, 10], 8], [3, 4]],
[[[5, 7, 7, 8, 8, 10], 6], [-1, -1]],
[[[2, 2], 2], [0, 1]]
]);

describe("34. Find First and Last Position of Element in Sorted Array", () => {
for (const [args, expected] of TEST_CASES) {
test(`when [${args[0].join(", ")}], ${args[1]}`, () => {
expect(searchRange(args[0], args[1])).toEqual(expected);
});
}
});
59 changes: 59 additions & 0 deletions solutions/findFirstAndLastPositionOfElementInSortedArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// 34. Find First and Last Position of Element in Sorted Array
// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
export default function searchRange(
nums: number[],
target: number
): [number, number] {
// binary search to find the first index
let from = 0;
let to = nums.length;

// loop until the search range shrinks to be from + 2 === to
while (to - from >= 3) {
const middle = Math.floor((from + to) / 2);

if (nums[middle] >= target) {
to = middle + 1;
} else {
from = middle;
}
}

// nums[from] or nums[to - 1] may point the target value
// otherwise, there's no target value
let first: number;

if (nums[from] === target) {
first = from;
} else if (nums[to - 1] === target) {
first = to - 1;
} else {
return [-1, -1];
}

// binary search to find the last index
from = first >= 0 ? first : 0;
to = nums.length;

// do the same binary search for the last index
while (to - from >= 3) {
const middle = Math.floor((from + to) / 2);

if (nums[middle] <= target) {
from = middle;
} else {
to = middle + 1;
}
}

let last: number;

// pick to-value first because the values both from and to point could be target
if (nums[to - 1] === target) {
last = to - 1;
} else if (nums[from] === target) {
last = from;
}

return [first, last!];
}