|
| 1 | +/** |
| 2 | + * @typedef {Object} BinaryMatrix |
| 3 | + * This is the BinaryMatrix's API interface. |
| 4 | + * You should not implement it, or speculate about its implementation |
| 5 | + * function BinaryMatrix() { |
| 6 | + * @param {integer} row, col |
| 7 | + * @return {integer} |
| 8 | + * this.get = function(row, col) { |
| 9 | + * ... |
| 10 | + * }; |
| 11 | + * |
| 12 | + * @return {[integer, integer]} |
| 13 | + * this.dimensions = function() { |
| 14 | + * ... |
| 15 | + * }; |
| 16 | + * }; |
| 17 | + */ |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {BinaryMatrix} binaryMatrix Class to interface with binary matrix. |
| 21 | + * @return {number} Index of leftmost column where '1' exists, or '-1' if none. |
| 22 | + * @summary Leftmost Column with atLeast a One {@link https://leetcode.com/problems/leftmost-column-with-at-least-a-one/} |
| 23 | + * @description Given a class to interface with binary matrix (where rows are ordered in ascending order), return leftmost column that contains a '1' or -1 if none. |
| 24 | + * Space O(R + C) - where R is number of rows, C is number of columns. |
| 25 | + * Time O(1) - always have 2 variables. |
| 26 | + */ |
| 27 | +const leftMostColumnWithOne = binaryMatrix => { |
| 28 | + const [rows, columns] = binaryMatrix.dimensions(); |
| 29 | + |
| 30 | + let row = 0; |
| 31 | + let col = columns - 1; |
| 32 | + |
| 33 | + while (row < rows && col >= 0) { |
| 34 | + if (binaryMatrix.get(row, col)) col--; |
| 35 | + else row++; |
| 36 | + } |
| 37 | + |
| 38 | + return col === columns - 1 ? -1 : col + 1; |
| 39 | +}; |
0 commit comments