|
| 1 | +/** |
| 2 | + * @param {number[]} arr |
| 3 | + * @param {number} m |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +const findLatestStep = function(arr, m) { |
| 7 | + const uF = new UnionFind(arr); |
| 8 | + const mRecords = new Set(); // This contains parents whose rank is m |
| 9 | + const visited = new Set(); |
| 10 | + let res = -1; |
| 11 | + |
| 12 | + for (let i = 0; i < arr.length; i++) { |
| 13 | + let val = arr[i]; |
| 14 | + visited.add(val); |
| 15 | + |
| 16 | + if (visited.has(val - 1)) { |
| 17 | + let parent1 = uF.find(val); |
| 18 | + let parent2 = uF.find(val - 1); |
| 19 | + // Since merging, the rank for val - 1 & val has changed, |
| 20 | + // they are no longer m. Hence removed them from set. |
| 21 | + mRecords.delete(parent1); |
| 22 | + mRecords.delete(parent2); |
| 23 | + uF.union(val, val - 1); |
| 24 | + } |
| 25 | + |
| 26 | + if (visited.has(val + 1)) { |
| 27 | + let parent1 = uF.find(val); |
| 28 | + let parent2 = uF.find(val + 1); |
| 29 | + mRecords.delete(parent1); |
| 30 | + mRecords.delete(parent2); |
| 31 | + uF.union(val, val + 1); |
| 32 | + } |
| 33 | + |
| 34 | + let parent = uF.find(val); |
| 35 | + if (uF.ranks.get(parent) === m) mRecords.add(parent); |
| 36 | + if (mRecords.size > 0) res = i + 1; |
| 37 | + } |
| 38 | + |
| 39 | + return res; |
| 40 | +}; |
| 41 | + |
| 42 | +class UnionFind { |
| 43 | + constructor(arr) { |
| 44 | + [this.parents, this.ranks] = this.initialise(arr); |
| 45 | + } |
| 46 | + |
| 47 | + initialise(arr) { |
| 48 | + const parents = new Map(); |
| 49 | + const ranks = new Map(); |
| 50 | + arr.forEach(val => { |
| 51 | + parents.set(val, val); |
| 52 | + ranks.set(val, 1); |
| 53 | + }) |
| 54 | + |
| 55 | + return [parents, ranks]; |
| 56 | + } |
| 57 | + |
| 58 | + find(val) { |
| 59 | + if (this.parents.get(val) === val) return val; |
| 60 | + this.parents.set(val, this.find(this.parents.get(val))); |
| 61 | + return this.parents.get(val); |
| 62 | + } |
| 63 | + |
| 64 | + union(m, n) { |
| 65 | + const rootM = this.find(m); |
| 66 | + const rootN = this.find(n); |
| 67 | + |
| 68 | + if (rootM === rootN) return; |
| 69 | + if (rootM > rootN) { |
| 70 | + this.updateParent(rootN, rootM); |
| 71 | + } else { |
| 72 | + this.updateParent(rootM, rootN); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + updateParent(child, parent) { |
| 77 | + this.ranks.set(parent, this.ranks.get(parent) + this.ranks.get(child)); |
| 78 | + this.parents.set(child, parent); |
| 79 | + } |
| 80 | +} |
0 commit comments