Repository navigation
Expand file tree
/
Copy pathstack_problems.py
More file actions
480 lines (397 loc) · 15.2 KB
/
Copy pathstack_problems.py
File metadata and controls
480 lines (397 loc) · 15.2 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
"""
STACK PROBLEMS & SOLUTIONS
==========================
Collection of well-known stack problems with optimal solutions.
Stack follows LIFO (Last In, First Out) principle - perfect for problems involving
nested structures, backtracking, and expression evaluation.
"""
# ============================================================================
# PROBLEM 1: VALID PARENTHESES
# ============================================================================
def is_valid_parentheses(s):
"""
Problem: Check if string of parentheses is valid.
Valid means: (), [], {} are properly opened and closed.
Approach: Use stack to match opening and closing brackets
Time Complexity: O(n)
Space Complexity: O(n)
Example: "()[]{}" → True, "([)]" → False
"""
# Stack to store opening brackets
stack = []
# Mapping of closing to opening brackets
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping: # Closing bracket
# Check if stack is empty or top doesn't match
if not stack or stack.pop() != mapping[char]:
return False
else: # Opening bracket
stack.append(char)
# Valid if all brackets are matched (stack is empty)
return not stack
# ============================================================================
# PROBLEM 2: EVALUATE REVERSE POLISH NOTATION (RPN)
# ============================================================================
def eval_rpn(tokens):
"""
Problem: Evaluate arithmetic expression in Reverse Polish Notation.
Approach: Use stack to store operands, apply operators when encountered
Time Complexity: O(n)
Space Complexity: O(n)
Example: ["2","1","+","3","*"] → ((2 + 1) * 3) = 9
"""
stack = []
operators = {'+', '-', '*', '/'}
for token in tokens:
if token in operators:
# Pop two operands (note the order!)
b = stack.pop()
a = stack.pop()
# Apply operation
if token == '+':
result = a + b
elif token == '-':
result = a - b
elif token == '*':
result = a * b
else: # token == '/'
# Integer division towards zero
result = int(a / b)
stack.append(result)
else:
# Push operand to stack
stack.append(int(token))
# Final result
return stack[0]
# ============================================================================
# PROBLEM 3: DAILY TEMPERATURES
# ============================================================================
def daily_temperatures(temperatures):
"""
Problem: Find how many days you have to wait for warmer temperature.
Approach: Monotonic decreasing stack
Time Complexity: O(n)
Space Complexity: O(n)
Example: [73,74,75,71,69,72,76,73] → [1,1,4,2,1,1,0,0]
"""
result = [0] * len(temperatures)
stack = [] # Store indices
for i, temp in enumerate(temperatures):
# While stack not empty and current temp > temp at stack top
while stack and temperatures[stack[-1]] < temp:
prev_index = stack.pop()
result[prev_index] = i - prev_index
stack.append(i)
return result
# ============================================================================
# PROBLEM 4: LARGEST RECTANGLE IN HISTOGRAM
# ============================================================================
def largest_rectangle_area(heights):
"""
Problem: Find area of largest rectangle in histogram.
Approach: Monotonic increasing stack
Time Complexity: O(n)
Space Complexity: O(n)
Logic: For each bar, find the largest rectangle with that bar as the shortest bar.
"""
stack = [] # Store indices
max_area = 0
for i, height in enumerate(heights):
# While current height < height at stack top
while stack and heights[stack[-1]] > height:
h = heights[stack.pop()]
# Width is current index - previous index in stack - 1
w = i if not stack else i - stack[-1] - 1
max_area = max(max_area, h * w)
stack.append(i)
# Process remaining bars in stack
while stack:
h = heights[stack.pop()]
w = len(heights) if not stack else len(heights) - stack[-1] - 1
max_area = max(max_area, h * w)
return max_area
# ============================================================================
# PROBLEM 5: MIN STACK
# ============================================================================
class MinStack:
"""
Problem: Design stack that supports push, pop, top, and getMin in O(1).
Approach: Use auxiliary stack to track minimums
Space Complexity: O(n)
"""
def __init__(self):
self.stack = []
self.min_stack = [] # Keeps track of minimums
def push(self, val):
"""Push element onto stack. O(1)"""
self.stack.append(val)
# Push to min_stack if it's empty or val <= current min
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self):
"""Remove top element. O(1)"""
if self.stack:
val = self.stack.pop()
# If popped value was minimum, remove from min_stack too
if val == self.min_stack[-1]:
self.min_stack.pop()
def top(self):
"""Get top element. O(1)"""
return self.stack[-1] if self.stack else None
def get_min(self):
"""Get minimum element. O(1)"""
return self.min_stack[-1] if self.min_stack else None
# ============================================================================
# PROBLEM 6: IMPLEMENT QUEUE USING STACKS
# ============================================================================
class MyQueue:
"""
Problem: Implement queue using only stacks.
Approach: Use two stacks - one for enqueue, one for dequeue
Amortized Time Complexity: O(1) for all operations
"""
def __init__(self):
self.input_stack = [] # For enqueue operations
self.output_stack = [] # For dequeue operations
def push(self, x):
"""Add element to back of queue."""
self.input_stack.append(x)
def pop(self):
"""Remove element from front of queue."""
self.peek() # Ensure output_stack has elements
return self.output_stack.pop()
def peek(self):
"""Get front element without removing."""
if not self.output_stack:
# Transfer all elements from input to output
while self.input_stack:
self.output_stack.append(self.input_stack.pop())
return self.output_stack[-1]
def empty(self):
"""Check if queue is empty."""
return not self.input_stack and not self.output_stack
# ============================================================================
# PROBLEM 7: NEXT GREATER ELEMENT
# ============================================================================
def next_greater_element(nums1, nums2):
"""
Problem: Find next greater element for each element in nums1 within nums2.
Approach: Monotonic decreasing stack + hash map
Time Complexity: O(n + m)
Space Complexity: O(n)
Example: nums1=[4,1,2], nums2=[1,3,4,2] → [-1,3,-1]
"""
# Build next greater element mapping for nums2
next_greater = {}
stack = []
for num in nums2:
# While stack not empty and current > stack top
while stack and stack[-1] < num:
next_greater[stack.pop()] = num
stack.append(num)
# For remaining elements in stack, no greater element exists
while stack:
next_greater[stack.pop()] = -1
# Build result for nums1
return [next_greater[num] for num in nums1]
# ============================================================================
# PROBLEM 8: SIMPLIFY PATH
# ============================================================================
def simplify_path(path):
"""
Problem: Simplify Unix-style file path.
Approach: Use stack to process path components
Time Complexity: O(n)
Space Complexity: O(n)
Example: "/a/./b/../../c/" → "/c"
"""
stack = []
components = path.split('/')
for component in components:
if component == '..' and stack:
stack.pop() # Go to parent directory
elif component and component != '.' and component != '..':
stack.append(component) # Valid directory name
# Ignore empty strings and '.'
return '/' + '/'.join(stack)
# ============================================================================
# PROBLEM 9: DECODE STRING
# ============================================================================
def decode_string(s):
"""
Problem: Decode string with pattern k[encoded_string].
Approach: Use stack to handle nested patterns
Time Complexity: O(n)
Space Complexity: O(n)
Example: "3[a2[c]]" → "accaccacc"
"""
stack = []
current_num = 0
current_string = ""
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == '[':
# Push current state to stack
stack.append((current_string, current_num))
current_string = ""
current_num = 0
elif char == ']':
# Pop and decode
prev_string, num = stack.pop()
current_string = prev_string + current_string * num
else:
current_string += char
return current_string
# ============================================================================
# PROBLEM 10: BASIC CALCULATOR
# ============================================================================
def calculate(s):
"""
Problem: Evaluate basic mathematical expression with +, -, (, ).
Approach: Use stack to handle parentheses
Time Complexity: O(n)
Space Complexity: O(n)
Example: "(1+(4+5+2)-3)+(6+8)" → 23
"""
stack = []
result = 0
number = 0
sign = 1 # 1 for +, -1 for -
for char in s:
if char.isdigit():
number = number * 10 + int(char)
elif char == '+':
result += sign * number
number = 0
sign = 1
elif char == '-':
result += sign * number
number = 0
sign = -1
elif char == '(':
# Push current result and sign to stack
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif char == ')':
# Complete current calculation
result += sign * number
number = 0
# Pop sign and previous result
result *= stack.pop() # sign
result += stack.pop() # previous result
return result + sign * number
# ============================================================================
# PROBLEM 11: ASTEROID COLLISION
# ============================================================================
def asteroid_collision(asteroids):
"""
Problem: Simulate asteroid collisions. Positive = right, negative = left.
Approach: Use stack to track surviving asteroids
Time Complexity: O(n)
Space Complexity: O(n)
Example: [5,10,-5] → [5,10] (10 and -5 collide, 10 survives)
"""
stack = []
for asteroid in asteroids:
while stack and asteroid < 0 < stack[-1]:
# Collision: right-moving meets left-moving
if stack[-1] < -asteroid:
stack.pop() # Right-moving asteroid explodes
continue
elif stack[-1] == -asteroid:
stack.pop() # Both explode
break # Left-moving asteroid explodes or both explode
else:
stack.append(asteroid) # No collision
return stack
# ============================================================================
# PROBLEM 12: REMOVE K DIGITS
# ============================================================================
def remove_k_digits(num, k):
"""
Problem: Remove k digits from number to make it smallest possible.
Approach: Monotonic increasing stack
Time Complexity: O(n)
Space Complexity: O(n)
Example: num="1432219", k=3 → "1219"
"""
stack = []
to_remove = k
for digit in num:
# Remove larger digits from stack
while stack and to_remove > 0 and stack[-1] > digit:
stack.pop()
to_remove -= 1
stack.append(digit)
# Remove remaining digits from end if needed
while to_remove > 0:
stack.pop()
to_remove -= 1
# Convert to string and handle edge cases
result = ''.join(stack).lstrip('0')
return result if result else '0'
# ============================================================================
# TEST FUNCTIONS
# ============================================================================
def test_stack_problems():
"""Test all stack problems with examples."""
print("=== STACK PROBLEMS & SOLUTIONS ===\n")
# Test 1: Valid Parentheses
print("1. VALID PARENTHESES")
test_cases = ["()", "()[]{}", "(]", "([)]", "{[]}"]
for case in test_cases:
print(f"'{case}' → {is_valid_parentheses(case)}")
# Test 2: Evaluate RPN
print("\n2. EVALUATE RPN")
rpn_tokens = ["2", "1", "+", "3", "*"]
print(f"{rpn_tokens} → {eval_rpn(rpn_tokens)}")
# Test 3: Daily Temperatures
print("\n3. DAILY TEMPERATURES")
temps = [73, 74, 75, 71, 69, 72, 76, 73]
print(f"Temperatures: {temps}")
print(f"Days to wait: {daily_temperatures(temps)}")
# Test 4: Largest Rectangle
print("\n4. LARGEST RECTANGLE IN HISTOGRAM")
heights = [2, 1, 5, 6, 2, 3]
print(f"Heights: {heights}")
print(f"Largest area: {largest_rectangle_area(heights)}")
# Test 5: Min Stack
print("\n5. MIN STACK")
min_stack = MinStack()
operations = [
("push", -2), ("push", 0), ("push", -3),
("getMin", None), ("pop", None), ("top", None), ("getMin", None)
]
for op, val in operations:
if op == "push":
min_stack.push(val)
print(f"Push {val}")
elif op == "pop":
min_stack.pop()
print("Pop")
elif op == "top":
print(f"Top: {min_stack.top()}")
elif op == "getMin":
print(f"Min: {min_stack.get_min()}")
# Test 6: Next Greater Element
print("\n6. NEXT GREATER ELEMENT")
nums1 = [4, 1, 2]
nums2 = [1, 3, 4, 2]
print(f"nums1: {nums1}, nums2: {nums2}")
print(f"Next greater: {next_greater_element(nums1, nums2)}")
# Test 7: Simplify Path
print("\n7. SIMPLIFY PATH")
paths = ["/home/", "/../", "/home//foo/", "/a/./b/../../c/"]
for path in paths:
print(f"'{path}' → '{simplify_path(path)}'")
# Test 8: Decode String
print("\n8. DECODE STRING")
encoded = ["3[a]2[bc]", "3[a2[c]]", "2[abc]3[cd]ef"]
for s in encoded:
print(f"'{s}' → '{decode_string(s)}'")
if __name__ == "__main__":
test_stack_problems()