-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCTCI.js
More file actions
112 lines (102 loc) · 1.95 KB
/
CTCI.js
File metadata and controls
112 lines (102 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// string
const checkUnique = (string) => {
const obj = {}
for (let i = 0; i < string.length; i++) {
let char = string[i];
if (obj[char] !== undefined) {
return false;
} else {
obj[char] = true;
}
}
return true;
}
const oneAway = (str1, str2) => {
if (str1 === str2) return true;
let hash = {}
for (let i = 0; i < str1.length; i++) {
if (hash[str1.charAt(i)] === undefined) {
hash[str1.charAt(i)] = 1;
} else {
hash[str1.charAt(i)] += 1;
}
}
let counter = 1;
for (let i = 0; i < str2.length; i++) {
if (hash[str2.charAt(i)] === undefined || hash[str2.charAt(i)] === 0) {
if (counter === 0) {
return false;
} else {
counter--;
}
} else {
hash[str2.charAt(i)] -= 1;
}
}
return true;
}
const zeroMatrix = (matrix) => {
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
let idxVal = matrix[i][j];
if (idxVal === 0) {
matrix[i] = new Array(matrix[i].length).fill(0);
for (let k = 0; k < matrix.length; k++) {
matrix[k][j] = 0;
}
return matrix;
}
}
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkList {
constructor() {
this.head = null;
}
appendNode(data) {
const newNode = new Node(data);
if (this.head === null) {
this.head = newNode;
return;
}
let curr = this.head;
while (curr.next) {
curr = curr.next;
}
curr.next = newNode;
}
removeNode(data) {
let curr = this.head;
if (this.head.data === data) {
this.head = this.head.next;
}
while (curr.next) {
if (curr.next.data === data) {
curr.next = curr.next.next;
return;
}
curr = curr.next;
}
}
}
const removeDup = (list) => {
let map = new Map();
let current = list.head;
let prev = null;
while (current) {
if (map.get(current.data) === undefined) {
map.set(current.data, 1)
prev = current;
} else {
prev.next = current.next
}
current = prev.next;
}
return list.head;
}