-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanswer1.js
More file actions
320 lines (261 loc) · 9.5 KB
/
Copy pathanswer1.js
File metadata and controls
320 lines (261 loc) · 9.5 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Number of Visible People in a Queue
/**
* Approach 1: Stack-based Solution (Optimal)
* Time Complexity: O(n) where n is the length of heights
* Space Complexity: O(n) for the stack
*/
const canSeePersonsCountApproach1 = (heights) => {
const n = heights.length;
const result = new Array(n).fill(0);
const stack = [];
// Traverse from right to left
for (let i = n - 1; i >= 0; i--) {
let count = 0;
// Pop elements from stack that are shorter than current height
while (stack.length > 0 && stack[stack.length - 1] < heights[i]) {
stack.pop();
count++;
}
// If stack is not empty, current person can see one more person (the one at top of stack)
result[i] = count + (stack.length > 0 ? 1 : 0);
// Push current height to stack
stack.push(heights[i]);
}
return result;
};
/**
* Approach 2: Brute Force Solution
* Time Complexity: O(n^2) where n is the length of heights
* Space Complexity: O(1) excluding the output array
*/
const canSeePersonsCountApproach2 = (heights) => {
const n = heights.length;
const result = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
let maxHeight = 0;
for (let j = i + 1; j < n; j++) {
// Person i can see person j if all people between them are shorter
if (heights[j] > maxHeight) {
result[i]++;
maxHeight = heights[j];
}
// If person j is taller or equal to person i, person i cannot see anyone beyond j
if (heights[j] >= heights[i]) {
break;
}
}
}
return result;
};
/**
* Approach 3: Monotonic Stack Solution with Detailed Tracking
* Time Complexity: O(n) where n is the length of heights
* Space Complexity: O(n) for the stack and auxiliary arrays
*/
const canSeePersonsCountApproach3 = (heights) => {
const n = heights.length;
const result = new Array(n).fill(0);
const stack = []; // Stack to store indices
// Traverse from right to left
for (let i = n - 1; i >= 0; i--) {
let count = 0;
// Pop elements from stack while current height is greater
while (stack.length > 0 && heights[stack[stack.length - 1]] < heights[i]) {
stack.pop();
count++;
}
// If stack is not empty, current person can see one more person
result[i] = count + (stack.length > 0 ? 1 : 0);
// Push current index to stack
stack.push(i);
}
return result;
};
/**
* Approach 4: Functional Programming Solution
* Time Complexity: O(n^2) where n is the length of heights
* Space Complexity: O(n) for intermediate arrays
*/
const canSeePersonsCountApproach4 = (heights) => {
return heights.map((height, i) => {
let count = 0;
let maxHeight = 0;
for (let j = i + 1; j < heights.length; j++) {
if (heights[j] > maxHeight) {
count++;
maxHeight = heights[j];
}
if (heights[j] >= height) {
break;
}
}
return count;
});
};
/**
* Approach 5: Recursive Solution with Memoization
* Time Complexity: O(n^2) in worst case, but with memoization can be better in some cases
* Space Complexity: O(n^2) for memoization table
*/
const canSeePersonsCountApproach5 = (heights) => {
const n = heights.length;
const memo = new Map();
const canSee = (i, j) => {
// Check if already computed
const key = `${i}-${j}`;
if (memo.has(key)) {
return memo.get(key);
}
// Base cases
if (j >= n) {
memo.set(key, false);
return false;
}
if (i === j) {
memo.set(key, false);
return false;
}
// Check if person j is blocked by someone between i and j
for (let k = i + 1; k < j; k++) {
if (heights[k] >= heights[i] || heights[k] >= heights[j]) {
memo.set(key, false);
return false;
}
}
memo.set(key, true);
return true;
};
const result = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (canSee(i, j)) {
result[i]++;
} else {
// If person i cannot see person j, they cannot see anyone beyond j
if (heights[j] >= heights[i]) {
break;
}
}
}
}
return result;
};
/**
* Approach 6: Generator-based Solution with Step-by-Step Visualization
* Time Complexity: O(n) where n is the length of heights
* Space Complexity: O(n) for the stack
*/
function* canSeePersonsCountGenerator(heights) {
yield { operation: 'init', heights };
const n = heights.length;
const result = new Array(n).fill(0);
const stack = [];
yield { operation: 'created_arrays', result: [...result], stack: [...stack] };
// Traverse from right to left
for (let i = n - 1; i >= 0; i--) {
yield { operation: 'processing_index', index: i, height: heights[i] };
let count = 0;
// Pop elements from stack that are shorter than current height
while (stack.length > 0 && stack[stack.length - 1] < heights[i]) {
const popped = stack.pop();
count++;
yield { operation: 'popped_shorter', popped, count, stack: [...stack] };
}
// If stack is not empty, current person can see one more person
result[i] = count + (stack.length > 0 ? 1 : 0);
yield { operation: 'updated_result', index: i, count: result[i], result: [...result] };
// Push current height to stack
stack.push(heights[i]);
yield { operation: 'pushed_to_stack', height: heights[i], stack: [...stack] };
}
yield { operation: 'complete', result: [...result] };
return result;
}
// Example usage and test cases
if (typeof window === 'undefined') { // Node.js environment
console.log('=== Testing Number of Visible People in a Queue Implementation ===');
const testHeights1 = [10, 6, 8, 5, 11, 9];
const expected1 = [3, 1, 2, 1, 1, 0];
const testHeights2 = [5, 1, 2, 3, 10];
const expected2 = [4, 1, 1, 1, 0];
// Test with approach 1
console.log('\n--- Testing Approach 1: Stack-based Solution ---');
console.log('Input:', testHeights1);
console.log('Expected:', expected1);
console.log('Result:', canSeePersonsCountApproach1([...testHeights1]));
console.log('\nInput:', testHeights2);
console.log('Expected:', expected2);
console.log('Result:', canSeePersonsCountApproach1([...testHeights2]));
// Test with approach 2
console.log('\n--- Testing Approach 2: Brute Force Solution ---');
console.log('Input:', testHeights1);
console.log('Expected:', expected1);
console.log('Result:', canSeePersonsCountApproach2([...testHeights1]));
console.log('\nInput:', testHeights2);
console.log('Expected:', expected2);
console.log('Result:', canSeePersonsCountApproach2([...testHeights2]));
// Test with approach 3
console.log('\n--- Testing Approach 3: Monotonic Stack Solution ---');
console.log('Input:', testHeights1);
console.log('Expected:', expected1);
console.log('Result:', canSeePersonsCountApproach3([...testHeights1]));
console.log('\nInput:', testHeights2);
console.log('Expected:', expected2);
console.log('Result:', canSeePersonsCountApproach3([...testHeights2]));
// Test with approach 4
console.log('\n--- Testing Approach 4: Functional Programming Solution ---');
console.log('Input:', testHeights1);
console.log('Expected:', expected1);
console.log('Result:', canSeePersonsCountApproach4([...testHeights1]));
console.log('\nInput:', testHeights2);
console.log('Expected:', expected2);
console.log('Result:', canSeePersonsCountApproach4([...testHeights2]));
// Test with approach 5
console.log('\n--- Testing Approach 5: Recursive Solution with Memoization ---');
console.log('Input:', testHeights1);
console.log('Expected:', expected1);
console.log('Result:', canSeePersonsCountApproach5([...testHeights1]));
console.log('\nInput:', testHeights2);
console.log('Expected:', expected2);
console.log('Result:', canSeePersonsCountApproach5([...testHeights2]));
// Test with approach 6
console.log('\n--- Testing Approach 6: Generator-based Solution ---');
console.log('Input:', testHeights1);
// Run generator
const runGenerator = async (generator) => {
let result;
do {
result = generator.next();
if (!result.done) {
console.log(' ', result.value);
}
} while (!result.done);
return result.value;
};
await runGenerator(canSeePersonsCountGenerator([...testHeights1]));
// Performance comparison utility
const performanceTest = (func, name, heights) => {
const start = performance.now();
func([...heights]);
const end = performance.now();
console.log(`${name}: ${end - start}ms for array of size ${heights.length}`);
};
// Run performance tests
console.log('\n=== Performance Comparison ===');
const testArray = Array.from({ length: 10000 }, () => Math.floor(Math.random() * 100000));
performanceTest(canSeePersonsCountApproach1, 'Approach 1 - Stack-based', testArray);
performanceTest(canSeePersonsCountApproach2, 'Approach 2 - Brute Force', testArray.slice(0, 1000)); // Smaller array for brute force
performanceTest(canSeePersonsCountApproach3, 'Approach 3 - Monotonic Stack', testArray);
performanceTest(canSeePersonsCountApproach4, 'Approach 4 - Functional', testArray.slice(0, 1000)); // Smaller array for functional
}
// Export functions for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
canSeePersonsCountApproach1,
canSeePersonsCountApproach2,
canSeePersonsCountApproach3,
canSeePersonsCountApproach4,
canSeePersonsCountApproach5,
canSeePersonsCountGenerator
};
}