|
| 1 | +// Is Unique: Implement an algorithm to determine if a string has all unique characters. |
| 2 | +// What if you cannot used additional data structures? |
| 3 | + |
| 4 | +const assert = require("assert"); |
| 5 | + |
| 6 | +/** |
| 7 | + * Checks if a string is composed of all unique characters |
| 8 | + * @param {string} str input string to check |
| 9 | + * @return {bool} Whether the input string contains unique characters |
| 10 | + * |
| 11 | + * We iterate through the input str of length N. Operations within this loop are O(1), so no additional time added. |
| 12 | + * We create an additional data structure, `set` where in the worst case is the same size as the input str, N. |
| 13 | + * |
| 14 | + * Runtime: O(N) |
| 15 | + * Space: O(N) |
| 16 | + * |
| 17 | + */ |
| 18 | +// with additional data structures |
| 19 | +const isUnique1 = (str) => { |
| 20 | + const strSet = new Set(); |
| 21 | + for (const s of str) { |
| 22 | + if (strSet.has(s)) return false; |
| 23 | + strSet.add(s); |
| 24 | + } |
| 25 | + return true; |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * Checks if a string is composed of all unique characters |
| 30 | + * @param {string} str input string to check |
| 31 | + * @return {bool} Whether the input string contains unique characters |
| 32 | + * |
| 33 | + * We iterate through the input str of length N. Within that, we iterate through the rest of the str of length N-1. |
| 34 | + * Within the nested for loop, we only perform an O(1) operation. This leads to O(N^2) for the runtime complexity. |
| 35 | + * In this implementation, we do not create any additional data structures, so we use constant space. |
| 36 | + * |
| 37 | + * Runtime: O(N^2) |
| 38 | + * Space: O(1) |
| 39 | + */ |
| 40 | +// without additional data structures |
| 41 | +const isUnique2 = (str) => { |
| 42 | + for (let i = 0; i < str.length - 1; i++) { |
| 43 | + for (let j = i + 1; j < str.length; j++) { |
| 44 | + if (str[i] === str[j]) return false; |
| 45 | + } |
| 46 | + } |
| 47 | + return true; |
| 48 | +}; |
| 49 | + |
| 50 | +describe(module.filename, () => { |
| 51 | + it("should return true on an input string with unique characters", () => { |
| 52 | + assert.equal(isUnique1("tech"), true); |
| 53 | + assert.equal(isUnique2("tech"), true); |
| 54 | + }); |
| 55 | + it("should return false on an input string with non-unique characters", () => { |
| 56 | + assert.equal(isUnique1("techqueria"), false); |
| 57 | + assert.equal(isUnique2("techqueria"), false); |
| 58 | + }); |
| 59 | +}); |
0 commit comments