diff --git a/automation/state.json b/automation/state.json index 093813f..e86eea9 100644 --- a/automation/state.json +++ b/automation/state.json @@ -1,4 +1,4 @@ { - "catalogIndex": 3, - "lastRunDate": "2026-10-23" + "catalogIndex": 4, + "lastRunDate": "2026-10-24" } diff --git a/problems/2026-10-24-binary-search/README.md b/problems/2026-10-24-binary-search/README.md new file mode 100644 index 0000000..b12af94 --- /dev/null +++ b/problems/2026-10-24-binary-search/README.md @@ -0,0 +1,28 @@ +# Binary Search + +## Problem + +Given a sorted array of integers `nums` and an integer `target`, return the index of `target` in `nums`, or `-1` if it is not present. + +You must write an algorithm with `O(log n)` runtime complexity. + +## Examples + +``` +Input: nums = [-1, 0, 3, 5, 9, 12], target = 9 +Output: 4 + +Input: nums = [-1, 0, 3, 5, 9, 12], target = 2 +Output: -1 +``` + +## Constraints + +- `1 <= nums.length <= 10^4` +- `-10^4 <= nums[i], target <= 10^4` +- All integers in `nums` are unique. +- `nums` is sorted ascending. + +## Notes + +Implement `search` in `solution.js`. diff --git a/problems/2026-10-24-binary-search/binary-search.test.js b/problems/2026-10-24-binary-search/binary-search.test.js new file mode 100644 index 0000000..3d1ae48 --- /dev/null +++ b/problems/2026-10-24-binary-search/binary-search.test.js @@ -0,0 +1,17 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { search } from "./solution.js"; + +describe("search", () => { + it("found", () => { + assert.equal(search([-1,0,3,5,9,12], 9), 4); + }); + + it("not found", () => { + assert.equal(search([-1,0,3,5,9,12], 2), -1); + }); + + it("single hit", () => { + assert.equal(search([5], 5), 0); + }); +}); diff --git a/problems/2026-10-24-binary-search/solution.js b/problems/2026-10-24-binary-search/solution.js new file mode 100644 index 0000000..0c9be2e --- /dev/null +++ b/problems/2026-10-24-binary-search/solution.js @@ -0,0 +1,16 @@ +/** + * @param {number[]} nums + * @param {number} target + * @returns {number} + */ +export function search(nums, target) { + let lo = 0; + let hi = nums.length - 1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (nums[mid] === target) return mid; + if (nums[mid] < target) lo = mid + 1; + else hi = mid - 1; + } + return -1; +}