def is_palindrome(node): if node is None or node.nxt is None: return True s = Stack() a = b = node s.push(b) l = 1 while a is not None and a.nxt is not None: a = a.nxt l += 1 b = b.nxt s.push(b) a = a.nxt if a: l += 1 s.pop() if l % 2 != 0: b = b.nxt while b is not None: if b.data != s.pop().data: return False b = b.nxt return True
def find_celebrity(array): s = Stack() for ppl in array: s.push(ppl) a = s.pop() b = s.pop() while not s.is_empty(): if does_a_know_b(a, b): a = s.pop() else: b = s.pop() if does_a_know_b(a, b): c = b else: c = a for person in array: if does_a_know_b(c, person) or not does_a_know_b(person, c): return None return c
def evaluate(exp): s = Stack() i = 0 while i < len(exp): if not is_operator(exp[i]): s.push(int(exp[i])) else: val1 = s.pop() val2 = s.pop() if exp[i] == '+': s.push(val1 + val2) elif exp[i] == '-': s.push(val2 - val1) elif exp[i] == '*': s.push(val1 * val2) elif exp[i] == '/': s.push(val2 / val1) else: s.push(val2 % val1) return s.pop()
def is_leaf_order_same(root1, root2): s1 = Stack() s2 = Stack() done1 = False done2 = False val1 = None val2 = None curr1 = root1 curr2 = root2 while True: while not done1: if curr1: s1.push(curr1) curr1 = curr1.left else: if s1.is_empty(): done1 = True val1 = None else: curr1 = s1.pop() val1 = curr1.data if is_leaf(curr1): done1 = True curr1 = curr1.right while not done2: if curr2: s2.push(curr2) curr2 = curr2.left else: if s2.is_empty(): done2 = True val2 = None else: curr2 = s2.pop() val2 = curr2.data if is_leaf(curr2): done2 = True curr2 = curr2.right if done1 and done2: if val1 != val2: return False else: done1 = False done2 = False if val1 is None and val2 is None: return True if val1 is None or val2 is None: return False
def is_sum_pair_present(root, target): s1 = Stack() s2 = Stack() done1 = False done2 = False val1 = None val2 = None curr1 = root curr2 = root while True: # in order while not done1: if curr1: s1.push(curr1) curr1 = curr1.left else: if s1.is_empty(): done1 = True else: curr1 = s1.pop() val1 = curr1.data curr1 = curr1.right done1 = True # reverse in order while not done2: if curr2: s2.push(curr2) curr2 = curr2.right else: if s2.is_empty(): done2 = True else: curr2 = s2.pop() val2 = curr2.data curr2 = curr2.left done2 = True # val1 != val2 makes sure that two of same values are not added if val1 != val2 and val1 + val2 == target: print 'pair found: {0} and {1}'.format(val1, val2) return True elif val1 + val2 < target: done1 = False elif val1 + val2 > target: done2 = False if val2 <= val1: return False
def is_valid(string): s = Stack() for c in string: if c == 'a': s.push(c) elif c == 'b' and not s.is_empty(): s.pop() else: return False return s.is_empty()
def nge(array): s = Stack() for num in array: while not s.is_empty() and s.peek() < num: print s.pop(), '-', num s.push(num) while not s.is_empty(): print s.pop(), '-', -1
def simplify_linux_dir_path(path): places = [p for p in path.split("/") if p != "." and p != ""] s = Stack() for p in places: if p == ".." and not s.is_empty(): s.pop() else: s.push(p) return "/" + '/'.join(s.get_list())
def build_lowest_number_removing_k_digits(num, k): s = Stack() l = len(num) - k for c in num: if not s.is_empty() and int(s.peek()) > int(c) and k > 0: s.pop() k -= 1 s.push(c) return ''.join(s.get_list()[:l])
def nge(array): _nge = [-1 for i in array] s = Stack() for i in range(len(array)): element = array[i] while not s.is_empty() and element > array[s.peek()]: _nge[s.peek()] = i s.pop() s.push(i) return _nge
def get_balanced_stack(string): s = Stack() for c in string: if c == '{' or s.is_empty(): s.push(c) else: if s.peek() == '{': s.pop() else: s.push(c) return s
def dupe_found(string): s = Stack() for c in string: exp = "" if c != ')': s.push(c) else: while not s.is_empty() and s.peek() != '(': char = s.pop() exp += char if not is_exp(exp): return True s.pop() return False
def largest_valid_substring(string): stack = Stack() l_index = None r_index = None min_index = None max_index = None max_diff = 0 for i in range(len(string)): if string[i] == '(': stack.push(i) elif string[i] == ')': try: l_index = stack.pop() r_index = i except Exception: pass if None not in [l_index, r_index]: diff = r_index - l_index if diff > max_diff: max_diff = diff min_index = l_index max_index = r_index if None in [l_index, r_index]: return None else: return string[min_index:max_index + 1]
def compute_left_smaller_diffs(array): s = Stack() diff_array = [None for i in array] for i in range(len(array)): element = array[i] while not s.is_empty() and s.peek() > element: s.pop() if s.is_empty(): diff_array[i] = 0 else: diff_array[i] = s.peek() s.push(element) return diff_array
def calculate_span(stocks): spans = [-1 for i in stocks] s = Stack() s.push(-1) spans[0] = 1 for i in range(len(stocks)): # pop until we find a taller element in stack while s.peek() != -1 and stocks[s.peek()] <= stocks[i]: s.pop() # calculate span spans[i] = i - s.peek() s.push(i) return spans
def iterative_post_order(root): s1 = Stack() s2 = Stack() s1.push(root) while not s1.is_empty(): node = s1.pop() if node.left: s1.push(node.left) if node.right: s1.push(node.right) s2.push(node) while not s2.is_empty(): print s2.pop(),
def find_largest_area(hist): s = Stack() n = len(hist) max_area = 0 i = 0 while i < n: # Push as long as stack top is smaller if s.is_empty() or hist[s.peek()] <= hist[i]: s.push(i) i += 1 else: # pop one by one and calculate area considering, the popped # elements height as the smallest. notice we are not # incrementing i here. Hence we keep popping until we find # a smaller height s_top = s.pop() # width is from top to i, but not including i width = i if s.is_empty() else i - s.peek() - 1 area_with_top_as_smallest = hist[s_top] * width if max_area < area_with_top_as_smallest: max_area = area_with_top_as_smallest # pop entire stack to consider all elements while not s.is_empty(): s_top = s.pop() # here i is N, so width will be from top to N, not # including N width = i if s.is_empty() else i - s.peek() - 1 area_with_top_as_smallest = hist[s_top] * width if max_area < area_with_top_as_smallest: max_area = area_with_top_as_smallest return max_area
class Queue2(object): def __init__(self): self.stack1 = Stack() self.stack2 = Stack() def push(self, element): self.stack1.push(element) def pop(self): if self.stack2.is_empty(): while not self.stack1.is_empty(): self.stack2.push(self.stack1.pop()) return self.stack2.pop() def peek(self): if self.stack2.is_empty(): while not self.stack1.is_empty(): self.stack2.push(self.stack1.pop()) return self.stack2.peek()
class Queue3(object): def __init__(self): self.stack = Stack() self.element_to_pop = None self.element_to_peek = None def push(self, element): self.stack.push(element) def _pop(self): if not self.stack.is_empty(): el = self.stack.pop() self._pop() if self.element_to_pop is None: self.element_to_pop = el else: self.stack.push(el) def _peek(self): if not self.stack.is_empty(): el = self.stack.pop() self._pop() if self.element_to_pop is None: self.element_to_pop = el self.stack.push(el) def pop(self): self._pop() el = self.element_to_pop self.element_to_pop = None return el def peek(self): self._pop() el = self.element_to_pop self.element_to_peek = None return el
def convert(exp): k = -1 exp = list(exp) s = Stack() for i in range(len(exp)): if is_operand(exp[i]): k += 1 exp[k] = exp[i] elif exp[i] == '(': s.push(exp[i]) elif exp[i] == ')': while not s.is_empty() and s.peek() != '(': k += 1 exp[k] = s.pop() if not s.is_empty() and s.peek() != '(': return -1 else: s.pop() # pop off the '(' else: while not s.is_empty() and precedence(exp[i]) <= precedence( s.peek()): k += 1 exp[k] = s.pop() s.push(exp[i]) while not s.is_empty(): k += 1 exp[k] = s.pop() return ''.join(exp)[0:k + 1]
def iterative_pre_order(root): s = Stack() s.push(root) while not s.is_empty(): node = s.pop() print node, if node.right: s.push(node.right) if node.left: s.push(node.left)
def find_max_len(string): n = len(string) result = 0 s = Stack() s.push(-1) for i in range(n): if string[i] == '(': s.push(i) else: s.pop() if not s.is_empty(): result = max(result, i - s.peek()) else: s.push(i) return result
def iterative_dfs(graph, source): s = Stack() s.push(source) visited = [False for i in graph.keys()] while not s.is_empty(): node = s.pop() visited[node] = True for neighbour in graph[node]: if not visited[neighbour]: s.push(neighbour)
def print_min_number(sequence): result = [] s = Stack() for i in range(len(sequence) + 1): s.push(i + 1) if i == len(sequence) or sequence[i] == 'I': while not s.is_empty(): result.append(s.pop()) print ''.join(map(str, result))
def is_pre_order(array): s = Stack() root = -maxint for value in array: while not s.is_empty() and s.peek() < value: root = s.pop() if value < root: return False s.push(value) return True
def spiral_print(root): s1 = Stack() s2 = Stack() s1.push(root) while not s1.is_empty() or not s2.is_empty(): while not s1.is_empty(): node = s1.pop() print node, if node.left: s2.push(node.left) if node.right: s2.push(node.right) while not s2.is_empty(): node = s2.pop() print node, if node.right: s1.push(node.right) if node.left: s1.push(node.left)
def merge_overlapping_intervals(array): # sort based on start time array.sort() s = Stack() s.push(array[0]) for i in range(1, len(array)): if not s.is_empty(): element = s.pop() curr_element = array[i] if is_overlapping(element, curr_element): s.push(merge(element, curr_element)) else: s.push(element) s.push(curr_element) print [(i.start, i.end) for i in s.items]
def print_common_nodes(root1, root2): s1 = Stack() s2 = Stack() while True: # push left nodes of trees to stack if root1: s1.push(root1) root1 = root1.left elif root2: s2.push(root2) root2 = root2.left elif not s1.is_empty() and not s2.is_empty(): root1 = s1.peek() root2 = s2.peek() if root1.data == root2.data: # found match, check next in both trees print root1.data, s1.pop() s2.pop() root1 = root1.right root2 = root2.right elif root1.data < root2.data: # move to next node in first tree s1.pop() root1 = root1.right # set this to none or in the next iteration it gets # pushed to s2 again root2 = None else: s2.pop() root2 = root2.right root1 = None else: break
def iterative_in_order(root): current = root s = Stack() done = False while not done: if current is not None: s.push(current) current = current.left else: if not s.is_empty(): current = s.pop() print current, current = current.right else: done = True
from G4G.Problems.stack.stack import Stack def insert_at_bottom(stack, element): if stack.is_empty(): stack.push(element) else: el = stack.pop() insert_at_bottom(stack, element) stack.push(el) def reverse_stack(stack): if not stack.is_empty(): el = stack.pop() reverse_stack(stack) insert_at_bottom(stack, el) if __name__ == '__main__': s = Stack() s.push(1) s.push(2) s.push(3) reverse_stack(s) while not s.is_empty(): print s.pop(),