code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python3 program to implement
# flood fill algorithm
# Dimensions of paint screen
M = 8
N = 8
# A recursive function to replace
# previous color 'prevC' at '(x, y)'
# and all surrounding pixels of (x, y)
# with new color 'newC' and
def floodFillUtil(screen, x, y, prevC, newC):
# Base cases
if (x < 0 or x >= M or y < 0 or
y >= N or screen[x][y] != prevC or
screen[x][y] == newC):
return
# Replace the color at (x, y)
screen[x][y] = newC
# Recur for north, east, south and west
floodFillUtil(screen, x + 1, y, prevC, newC)
floodFillUtil(screen, x - 1, y, prevC, newC)
floodFillUtil(screen, x, y + 1, prevC, newC)
floodFillUtil(screen, x, y - 1, prevC, newC)
# It mainly finds the previous color on (x, y) and
# calls floodFillUtil()
def floodFill(screen, x, y, newC):
prevC = screen[x][y]
if(prevC==newC):
return
floodFillUtil(screen, x, y, prevC, newC)
# Driver Code
screen = [[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 0],
[1, 0, 0, 1, 1, 0, 1, 1],
[1, 2, 2, 2, 2, 0, 1, 0],
[1, 1, 1, 2, 2, 0, 1, 0],
[1, 1, 1, 2, 2, 2, 2, 0],
[1, 1, 1, 1, 1, 2, 1, 1],
[1, 1, 1, 1, 1, 2, 2, 1]]
x = 4
y = 4
newC = 3
floodFill(screen, x, y, newC)
print ("Updated screen after call to floodFill:")
for i in range(M):
for j in range(N):
print(screen[i][j], end = ' ')
print()
# This code is contributed by Ashutosh450
# Updated by Arun Pandey
|
quadratic
|
quadratic
|
# Python3 program for above approach
# Function to check valid coordinate
def validCoord(x, y, n, m):
if x < 0 or y < 0:
return 0
if x >= n or y >= m:
return 0
return 1
# Function to run bfs
def bfs(n, m, data, X, Y, color):
# Visiting array
vis = [[0 for i in range(101)] for j in range(101)]
# Creating queue for bfs
obj = []
# Pushing pair of {x, y}
obj.append([X, Y])
# Marking {x, y} as visited
vis[X][Y] = 1
# Until queue is empty
while len(obj) > 0:
# Extracting front pair
coord = obj[0]
x = coord[0]
y = coord[1]
preColor = data[x][y]
data[x][y] = color
# Popping front pair of queue
obj.pop(0)
# For Upside Pixel or Cell
if validCoord(x + 1, y, n, m) == 1 and vis[x + 1][y] == 0 and data[x + 1][y] == preColor:
obj.append([x + 1, y])
vis[x + 1][y] = 1
# For Downside Pixel or Cell
if validCoord(x - 1, y, n, m) == 1 and vis[x - 1][y] == 0 and data[x - 1][y] == preColor:
obj.append([x - 1, y])
vis[x - 1][y] = 1
# For Right side Pixel or Cell
if validCoord(x, y + 1, n, m) == 1 and vis[x][y + 1] == 0 and data[x][y + 1] == preColor:
obj.append([x, y + 1])
vis[x][y + 1] = 1
# For Left side Pixel or Cell
if validCoord(x, y - 1, n, m) == 1 and vis[x][y - 1] == 0 and data[x][y - 1] == preColor:
obj.append([x, y - 1])
vis[x][y - 1] = 1
# Printing The Changed Matrix Of Pixels
for i in range(n):
for j in range(m):
print(data[i][j], end = " ")
print()
print()
n = 8
m = 8
data = [
[ 1, 1, 1, 1, 1, 1, 1, 1 ],
[ 1, 1, 1, 1, 1, 1, 0, 0 ],
[ 1, 0, 0, 1, 1, 0, 1, 1 ],
[ 1, 2, 2, 2, 2, 0, 1, 0 ],
[ 1, 1, 1, 2, 2, 0, 1, 0 ],
[ 1, 1, 1, 2, 2, 2, 2, 0 ],
[ 1, 1, 1, 1, 1, 2, 1, 1 ],
[ 1, 1, 1, 1, 1, 2, 2, 1 ],
]
x, y, color = 4, 4, 3
# Function Call
bfs(n, m, data, x, y, color)
# This code is contributed by decode2207.
|
quadratic
|
quadratic
|
# A simple Python 3 program to find sum
# of all subsquares of size k x k
# Size of given matrix
n = 5
# A simple function to find sum of all
# sub-squares of size k x k in a given
# square matrix of size n x n
def printSumSimple(mat, k):
# k must be smaller than or equal to n
if (k > n):
return
# row number of first cell in current
# sub-square of size k x k
for i in range(n - k + 1):
# column of first cell in current
# sub-square of size k x k
for j in range(n - k + 1):
# Calculate and print sum of
# current sub-square
sum = 0
for p in range(i, k + i):
for q in range(j, k + j):
sum += mat[p][q]
print(sum, end = " ")
# Line separator for sub-squares
# starting with next row
print()
# Driver Code
if __name__ == "__main__":
mat = [[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]]
k = 3
printSumSimple(mat, k)
# This code is contributed by ita_c
|
constant
|
quadratic
|
# An efficient Python3 program to find sum
# of all subsquares of size k x k
# A O(n^2) function to find sum of all
# sub-squares of size k x k in a given
# square matrix of size n x n
def printSumTricky(mat, k):
global n
# k must be smaller than or
# equal to n
if k > n:
return
# 1: PREPROCESSING
# To store sums of all strips of size k x 1
stripSum = [[None] * n for i in range(n)]
# Go column by column
for j in range(n):
# Calculate sum of first k x 1
# rectangle in this column
Sum = 0
for i in range(k):
Sum += mat[i][j]
stripSum[0][j] = Sum
# Calculate sum of remaining rectangles
for i in range(1, n - k + 1):
Sum += (mat[i + k - 1][j] -
mat[i - 1][j])
stripSum[i][j] = Sum
# 2: CALCULATE SUM of Sub-Squares
# using stripSum[][]
for i in range(n - k + 1):
# Calculate and print sum of first
# subsquare in this row
Sum = 0
for j in range(k):
Sum += stripSum[i][j]
print(Sum, end = " ")
# Calculate sum of remaining squares
# in current row by removing the leftmost
# strip of previous sub-square and adding
# a new strip
for j in range(1, n - k + 1):
Sum += (stripSum[i][j + k - 1] -
stripSum[i][j - 1])
print(Sum, end = " ")
print()
# Driver Code
n = 5
mat = [[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5]]
k = 3
printSumTricky(mat, k)
# This code is contributed by PranchalK
|
quadratic
|
quadratic
|
# Python3 Program to find
# transpose of a matrix
N = 4
# This function stores
# transpose of A[][] in B[][]
def transpose(A, B):
for i in range(N):
for j in range(N):
B[i][j] = A[j][i]
# Driver code
if __name__ == '__main__':
A = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
# To store result
B = [[0 for x in range(N)] for y in range(N)]
# Function call
transpose(A, B)
print("Result matrix is")
for i in range(N):
for j in range(N):
print(B[i][j], " ", end='')
print()
|
quadratic
|
quadratic
|
# Python3 Program to find
# transpose of a matrix
N = 4
# Finds transpose of A[][] in-place
def transpose(A):
for i in range(N):
for j in range(i+1, N):
A[i][j], A[j][i] = A[j][i], A[i][j]
# driver code
A = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
transpose(A)
print("Modified matrix is")
for i in range(N):
for j in range(N):
print(A[i][j], " ", end='')
print()
# This code is contributed
# by Anant Agarwal.
|
constant
|
quadratic
|
# Python3 program for addition
# of two matrices
N = 4
# This function adds A[][]
# and B[][], and stores
# the result in C[][]
def add(A, B, C):
for i in range(N):
for j in range(N):
C[i][j] = A[i][j] + B[i][j]
# driver code
A = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
B = [[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]]
C = A[:][:] # To store result
add(A, B, C)
print("Result matrix is")
for i in range(N):
for j in range(N):
print(C[i][j], " ", end='')
print()
# This code is contributed
# by Anant Agarwal.
|
quadratic
|
quadratic
|
# A Memoization based program to find maximum collection
# using two traversals of a grid
R=5
C=4
intmin=-10000000
intmax=10000000
# checks whether a given input is valid or not
def isValid(x,y1,y2):
return ((x >= 0 and x < R and y1 >=0
and y1 < C and y2 >=0 and y2 < C))
# Driver function to collect max value
def getMaxUtil(arr,mem,x,y1,y2):
# ---------- BASE CASES -----------
if isValid(x, y1, y2)==False:
return intmin
# if both traversals reach their destinations
if x == R-1 and y1 == 0 and y2 == C-1:
if y1==y2:
return arr[x][y1]
else:
return arr[x][y1]+arr[x][y2]
# If both traversals are at last row
# but not at their destination
if x==R-1:
return intmin
# If subproblem is already solved
if mem[x][y1][y2] != -1:
return mem[x][y1][y2]
# Initialize answer for this subproblem
ans=intmin
# this variable is used to store gain of current cell(s)
temp=0
if y1==y2:
temp=arr[x][y1]
else:
temp=arr[x][y1]+arr[x][y2]
# Recur for all possible cases, then store and return the
# one with max value
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2-1))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2+1))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1, y2))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2-1))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1-1, y2+1))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2-1))
ans = max(ans, temp + getMaxUtil(arr, mem, x+1, y1+1, y2+1))
mem[x][y1][y2] = ans
return ans
# This is mainly a wrapper over recursive
# function getMaxUtil().
# This function creates a table for memoization and calls
# getMaxUtil()
def geMaxCollection(arr):
# Create a memoization table and
# initialize all entries as -1
mem=[[[-1 for i in range(C)] for i in range(C)] for i in range(R)]
# Calculation maximum value using
# memoization based function
# getMaxUtil()
return getMaxUtil(arr, mem, 0, 0, C-1)
# Driver program to test above functions
if __name__=='__main__':
arr=[[3, 6, 8, 2],
[5, 2, 4, 3],
[1, 1, 20, 10],
[1, 1, 20, 10],
[1, 1, 20, 10],
]
print('Maximum collection is ', geMaxCollection(arr))
#this code is contributed by sahilshelangia
|
quadratic
|
cubic
|
# A Naive Recursive Python program to
# count paths with exactly 'k' coins
R = 3
C = 3
# Recursive function to count paths
# with sum k from (0, 0) to (m, n)
def pathCountRec(mat, m, n, k):
# Base cases
if m < 0 or n < 0 or k < 0:
return 0
elif m == 0 and n == 0:
return k == mat[m][n]
# #(m, n) can be reached either
# through (m-1, n) or through
# (m, n-1)
return (pathCountRec(mat, m-1, n, k-mat[m][n])
+ pathCountRec(mat, m, n-1, k-mat[m][n]))
# A wrapper over pathCountRec()
def pathCount(mat, k):
return pathCountRec(mat, R-1, C-1, k)
# Driver Program
k = 12
mat = [[1, 2, 3],
[4, 6, 5],
[3, 2, 1]]
print(pathCount(mat, k))
# This code is contributed by Shrikant13.
|
quadratic
|
linear
|
# A Dynamic Programming based Python3 program to
# count paths with exactly 'k' coins
R = 3
C = 3
MAX_K = 1000
def pathCountDPRecDP(mat, m, n, k):
# Base cases
if m < 0 or n < 0 or k < 0:
return 0
elif m == 0 and n == 0:
return k == mat[m][n]
# If this subproblem is already solved
if (dp[m][n][k] != -1):
return dp[m][n][k]
# #(m, n) can be reached either
# through (m-1, n) or through
# (m, n-1)
dp[m][n][k] = (pathCountDPRecDP(mat, m - 1, n, k - mat[m][n]) +
pathCountDPRecDP(mat, m, n - 1, k - mat[m][n]))
return dp[m][n][k]
# A wrapper over pathCountDPRecDP()
def pathCountDP(mat, k):
return pathCountDPRecDP(mat, R - 1, C - 1, k)
# Driver Code
k = 12
# Initialising dp[][][]
dp = [[ [-1 for col in range(MAX_K)]
for col in range(C)]
for row in range(R)]
mat = [[1, 2, 3],
[4, 6, 5],
[3, 2, 1]]
print(pathCountDP(mat, k))
# This code is contributed by ashutosh450
|
quadratic
|
quadratic
|
# Python3 program to find the longest path in a matrix
# with given constraints
n = 3
# Returns length of the longest path beginning with mat[i][j].
# This function mainly uses lookup table dp[n][n]
def findLongestFromACell(i, j, mat, dp):
# Base case
if (i < 0 or i >= n or j < 0 or j >= n):
return 0
# If this subproblem is already solved
if (dp[i][j] != -1):
return dp[i][j]
# To store the path lengths in all the four directions
x, y, z, w = -1, -1, -1, -1
# Since all numbers are unique and in range from 1 to n * n,
# there is atmost one possible direction from any cell
if (j < n-1 and ((mat[i][j] + 1) == mat[i][j + 1])):
x = 1 + findLongestFromACell(i, j + 1, mat, dp)
if (j > 0 and (mat[i][j] + 1 == mat[i][j-1])):
y = 1 + findLongestFromACell(i, j-1, mat, dp)
if (i > 0 and (mat[i][j] + 1 == mat[i-1][j])):
z = 1 + findLongestFromACell(i-1, j, mat, dp)
if (i < n-1 and (mat[i][j] + 1 == mat[i + 1][j])):
w = 1 + findLongestFromACell(i + 1, j, mat, dp)
# If none of the adjacent fours is one greater we will take 1
# otherwise we will pick maximum from all the four directions
dp[i][j] = max(x, max(y, max(z, max(w, 1))))
return dp[i][j]
# Returns length of the longest path beginning with any cell
def finLongestOverAll(mat):
result = 1 # Initialize result
# Create a lookup table and fill all entries in it as -1
dp = [[-1 for i in range(n)]for i in range(n)]
# Compute longest path beginning from all cells
for i in range(n):
for j in range(n):
if (dp[i][j] == -1):
findLongestFromACell(i, j, mat, dp)
# Update result if needed
result = max(result, dp[i][j])
return result
# Driver program
mat = [[1, 2, 9],
[5, 3, 8],
[4, 6, 7]]
print("Length of the longest path is ", finLongestOverAll(mat))
# this code is improved by sahilshelangia
|
quadratic
|
quadratic
|
# Python3 program to find minimum initial
# points to reach destination
import math as mt
R = 3
C = 3
def minInitialPoints(points):
'''
dp[i][j] represents the minimum initial
points player should have so that when
starts with cell(i, j) successfully
reaches the destination cell(m-1, n-1)
'''
dp = [[0 for x in range(C + 1)]
for y in range(R + 1)]
m, n = R, C
if points[m - 1][n - 1] > 0:
dp[m - 1][n - 1] = 1
else:
dp[m - 1][n - 1] = abs(points[m - 1][n - 1]) + 1
'''
Fill last row and last column as base
to fill entire table
'''
for i in range(m - 2, -1, -1):
dp[i][n - 1] = max(dp[i + 1][n - 1] -
points[i][n - 1], 1)
for i in range(n - 2, -1, -1):
dp[m - 1][i] = max(dp[m - 1][i + 1] -
points[m - 1][i], 1)
'''
fill the table in bottom-up fashion
'''
for i in range(m - 2, -1, -1):
for j in range(n - 2, -1, -1):
min_points_on_exit = min(dp[i + 1][j],
dp[i][j + 1])
dp[i][j] = max(min_points_on_exit -
points[i][j], 1)
return dp[0][0]
# Driver code
points = [[-2, -3, 3],
[-5, -10, 1],
[10, 30, -5]]
print("Minimum Initial Points Required:",
minInitialPoints(points))
# This code is contributed by
# Mohit kumar 29 (IIIT gwalior)
|
quadratic
|
quadratic
|
# Python3 program to find maximum sum
# subarray in a given 2D array
# Implementation of Kadane's algorithm
# for 1D array. The function returns the
# maximum sum and stores starting and
# ending indexes of the maximum sum subarray
# at addresses pointed by start and finish
# pointers respectively.
def kadane(arr, start, finish, n):
# initialize sum, maxSum and
Sum = 0
maxSum = -999999999999
i = None
# Just some initial value to check
# for all negative values case
finish[0] = -1
# local variable
local_start = 0
for i in range(n):
Sum += arr[i]
if Sum < 0:
Sum = 0
local_start = i + 1
elif Sum > maxSum:
maxSum = Sum
start[0] = local_start
finish[0] = i
# There is at-least one
# non-negative number
if finish[0] != -1:
return maxSum
# Special Case: When all numbers
# in arr[] are negative
maxSum = arr[0]
start[0] = finish[0] = 0
# Find the maximum element in array
for i in range(1, n):
if arr[i] > maxSum:
maxSum = arr[i]
start[0] = finish[0] = i
return maxSum
# The main function that finds maximum
# sum rectangle in M[][]
def findMaxSum(M):
global ROW, COL
# Variables to store the final output
maxSum, finalLeft = -999999999999, None
finalRight, finalTop, finalBottom = None, None, None
left, right, i = None, None, None
temp = [None] * ROW
Sum = 0
start = [0]
finish = [0]
# Set the left column
for left in range(COL):
# Initialize all elements of temp as 0
temp = [0] * ROW
# Set the right column for the left
# column set by outer loop
for right in range(left, COL):
# Calculate sum between current left
# and right for every row 'i'
for i in range(ROW):
temp[i] += M[i][right]
# Find the maximum sum subarray in
# temp[]. The kadane() function also
# sets values of start and finish.
# So 'sum' is sum of rectangle between
# (start, left) and (finish, right) which
# is the maximum sum with boundary columns
# strictly as left and right.
Sum = kadane(temp, start, finish, ROW)
# Compare sum with maximum sum so far.
# If sum is more, then update maxSum
# and other output values
if Sum > maxSum:
maxSum = Sum
finalLeft = left
finalRight = right
finalTop = start[0]
finalBottom = finish[0]
# Prfinal values
print("(Top, Left)", "(", finalTop,
finalLeft, ")")
print("(Bottom, Right)", "(", finalBottom,
finalRight, ")")
print("Max sum is:", maxSum)
# Driver Code
ROW = 4
COL = 5
M = [[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]]
# Function call
findMaxSum(M)
# This code is contributed by PranchalK
|
linear
|
cubic
|
# Program to implement a stack using
# two queue
from _collections import deque
class Stack:
def __init__(self):
# Two inbuilt queues
self.q1 = deque()
self.q2 = deque()
def push(self, x):
# Push x first in empty q2
self.q2.append(x)
# Push all the remaining
# elements in q1 to q2.
while (self.q1):
self.q2.append(self.q1.popleft())
# swap the names of two queues
self.q1, self.q2 = self.q2, self.q1
def pop(self):
# if no elements are there in q1
if self.q1:
self.q1.popleft()
def top(self):
if (self.q1):
return self.q1[0]
return None
def size(self):
return len(self.q1)
# Driver Code
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print("current size: ", s.size())
print(s.top())
s.pop()
print(s.top())
s.pop()
print(s.top())
print("current size: ", s.size())
# This code is contributed by PranchalK
|
linear
|
linear
|
# Program to implement a stack using
# two queue
from _collections import deque
class Stack:
def __init__(self):
# Two inbuilt queues
self.q1 = deque()
self.q2 = deque()
def push(self, x):
self.q1.append(x)
def pop(self):
# if no elements are there in q1
if (not self.q1):
return
# Leave one element in q1 and push others in q2
while(len(self.q1) != 1):
self.q2.append(self.q1.popleft())
# swap the names of two queues
self.q1, self.q2 = self.q2, self.q1
def top(self):
# if no elements are there in q1
if (not self.q1):
return
# Leave one element in q1 and push others in q2
while(len(self.q1) != 1):
self.q2.append(self.q1.popleft())
# Pop the only left element from q1 to q2
top = self.q1[0]
self.q2.append(self.q1.popleft())
# swap the names of two queues
self.q1, self.q2 = self.q2, self.q1
return top
def size(self):
return len(self.q1)
# Driver Code
if __name__ == '__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print("current size: ", s.size())
print(s.top())
s.pop()
print(s.top())
s.pop()
print(s.top())
print("current size: ", s.size())
# This code is contributed by jainlovely450
|
linear
|
linear
|
from _collections import deque
# Stack Class that acts as a queue
class Stack:
def __init__(self):
self.q = deque()
# Push operation
def push(self, data):
# Get previous size of queue
s = len(self.q)
# Push the current element
self.q.append(data)
# Pop all the previous elements and put them after
# current element
for i in range(s):
self.q.append(self.q.popleft())
# Removes the top element
def pop(self):
if (not self.q):
print("No elements")
else:
self.q.popleft()
# Returns top of stack
def top(self):
if (not self.q):
return
return self.q[0]
def size(self):
return len(self.q)
if __name__ == '__main__':
st = Stack()
st.push(1)
st.push(2)
st.push(3)
print("current size: ", st.size())
print(st.top())
st.pop()
print(st.top())
st.pop()
print(st.top())
print("current size: ", st.size())
|
linear
|
linear
|
# Python3 program to demonstrate linked list
# based implementation of queue
# A linked list (LL) node
# to store a queue entry
class Node:
def __init__(self, data):
self.data = data
self.next = None
# A class to represent a queue
# The queue, front stores the front node
# of LL and rear stores the last node of LL
class Queue:
def __init__(self):
self.front = self.rear = None
def isEmpty(self):
return self.front == None
# Method to add an item to the queue
def EnQueue(self, item):
temp = Node(item)
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
# Method to remove an item from queue
def DeQueue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.rear = None
# Driver Code
if __name__ == '__main__':
q = Queue()
q.EnQueue(10)
q.EnQueue(20)
q.DeQueue()
q.DeQueue()
q.EnQueue(30)
q.EnQueue(40)
q.EnQueue(50)
q.DeQueue()
print("Queue Front : " + str(q.front.data))
print("Queue Rear : " + str(q.rear.data))
|
constant
|
constant
|
# Python implementation of De-queue using circular
# array
# A structure to represent a Deque
MAX = 100
class Deque:
def __init__(self, size):
self.arr = [0] * MAX
self.front = -1
self.rear = 0
self.size = size
''' Operations on Deque:
void insertfront(int key);
void insertrear(int key);
void deletefront();
void deleterear();
bool isFull();
bool isEmpty();
int getFront();
int getRear(); '''
# Checks whether Deque is full or not.
def isFull(self):
return ((self.front == 0 and self.rear == self.size-1) or self.front == self.rear + 1)
# Checks whether Deque is empty or not.
def isEmpty(self):
return (self.front == -1)
# Inserts an element at front
def insertfront(self, key):
# check whether Deque if full or not
if (self.isFull()):
print("Overflow")
return
# If queue is initially empty
if (self.front == -1):
self.front = 0
self.rear = 0
# front is at first position of queue
elif (self.front == 0):
self.front = self.size - 1
else: # decrement front end by '1'
self.front = self.front-1
# insert current element into Deque
self.arr[self.front] = key
# function to inset element at rear end
# of Deque.
def insertrear(self, key):
if (self.isFull()):
print(" Overflow")
return
# If queue is initially empty
if (self.front == -1):
self.front = 0
self.rear = 0
# rear is at last position of queue
elif (self.rear == self.size-1):
self.rear = 0
# increment rear end by '1'
else:
self.rear = self.rear+1
# insert current element into Deque
self.arr[self.rear] = key
# Deletes element at front end of Deque
def deletefront(self):
# check whether Deque is empty or not
if (self.isEmpty()):
print("Queue Underflow")
return
# Deque has only one element
if (self.front == self.rear):
self.front = -1
self.rear = -1
else:
# back to initial position
if (self.front == self.size - 1):
self.front = 0
else: # increment front by '1' to remove current
# front value from Deque
self.front = self.front+1
# Delete element at rear end of Deque
def deleterear(self):
if (self.isEmpty()):
print(" Underflow")
return
# Deque has only one element
if (self.front == self.rear):
self.front = -1
self.rear = -1
elif (self.rear == 0):
self.rear = self.size-1
else:
self.rear = self.rear-1
# Returns front element of Deque
def getFront(self):
# check whether Deque is empty or not
if (self.isEmpty()):
print(" Underflow")
return -1
return self.arr[self.front]
# function return rear element of Deque
def getRear(self):
# check whether Deque is empty or not
if(self.isEmpty() or self.rear < 0):
print(" Underflow")
return -1
return self.arr[self.rear]
# Driver code
if __name__ == "__main__":
dq = Deque(5)
# Function calls
print("Insert element at rear end : 5 ")
dq.insertrear(5)
print("insert element at rear end : 10 ")
dq.insertrear(10)
print(f"get rear element : {dq.getRear()}")
dq.deleterear()
print(f"After delete rear element new rear become : {dq.getRear()}")
print("inserting element at front end")
dq.insertfront(15)
print(f"get front element: {dq.getFront()}")
dq.deletefront()
print(f"After delete front element new front become : {dq.getFront()}")
# This code is contributed by _saurabh_jaiswal
|
linear
|
linear
|
# Recursive Python program for level
# order traversal of Binary Tree
# A node structure
class Node:
# A utility function to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Function to print level order traversal of tree
def printLevelOrder(root):
h = height(root)
for i in range(1, h+1):
printCurrentLevel(root, i)
# Print nodes at a current level
def printCurrentLevel(root, level):
if root is None:
return
if level == 1:
print(root.data, end=" ")
elif level > 1:
printCurrentLevel(root.left, level-1)
printCurrentLevel(root.right, level-1)
""" Compute the height of a tree--the number of nodes
along the longest path from the root node down to
the farthest leaf node
"""
def height(node):
if node is None:
return 0
else:
# Compute the height of each subtree
lheight = height(node.left)
rheight = height(node.right)
# Use the larger one
if lheight > rheight:
return lheight+1
else:
return rheight+1
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Level order traversal of binary tree is -")
printLevelOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
quadratic
|
# Python program to print level
# order traversal using Queue
# A node structure
class Node:
# A utility function to create a new node
def __init__(self, key):
self.data = key
self.left = None
self.right = None
# Iterative Method to print the
# height of a binary tree
def printLevelOrder(root):
# Base Case
if root is None:
return
# Create an empty queue
# for level order traversal
queue = []
# Enqueue Root and initialize height
queue.append(root)
while(len(queue) > 0):
# Print front of queue and
# remove it from queue
print(queue[0].data, end = " ")
node = queue.pop(0)
# Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
# Driver Program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Level Order Traversal of binary tree is -")
printLevelOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python program to create a Complete Binary Tree from
# its linked list representation
# Linked List node
class ListNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.next = None
# Binary Tree Node structure
class BinaryTreeNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Class to convert the linked list to Binary Tree
class Conversion:
# Constructor for storing head of linked list
# and root for the Binary Tree
def __init__(self, data = None):
self.head = None
self.root = None
def push(self, new_data):
# Creating a new linked list node and storing data
new_node = ListNode(new_data)
# Make next of new node as head
new_node.next = self.head
# Move the head to point to new node
self.head = new_node
def convertList2Binary(self):
# Queue to store the parent nodes
q = []
# Base Case
if self.head is None:
self.root = None
return
# 1.) The first node is always the root node,
# and add it to the queue
self.root = BinaryTreeNode(self.head.data)
q.append(self.root)
# Advance the pointer to the next node
self.head = self.head.next
# Until the end of linked list is reached, do:
while(self.head):
# 2.a) Take the parent node from the q and
# and remove it from q
parent = q.pop(0) # Front of queue
# 2.c) Take next two nodes from the linked list.
# We will add them as children of the current
# parent node in step 2.b.
# Push them into the queue so that they will be
# parent to the future node
leftChild= None
rightChild = None
leftChild = BinaryTreeNode(self.head.data)
q.append(leftChild)
self.head = self.head.next
if(self.head):
rightChild = BinaryTreeNode(self.head.data)
q.append(rightChild)
self.head = self.head.next
#2.b) Assign the left and right children of parent
parent.left = leftChild
parent.right = rightChild
def inorderTraversal(self, root):
if(root):
self.inorderTraversal(root.left)
print (root.data,end=" ")
self.inorderTraversal(root.right)
# Driver Program to test above function
# Object of conversion class
conv = Conversion()
conv.push(36)
conv.push(30)
conv.push(25)
conv.push(15)
conv.push(12)
conv.push(10)
conv.convertList2Binary()
print ("Inorder Traversal of the constructed Binary Tree is:")
conv.inorderTraversal(conv.root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
np
|
linear
|
# Python Program to print zigzag traversal
# of binary tree
# Binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = self.right = None
# function to print zigzag traversal of
# binary tree
def zizagtraversal(root):
# Base Case
if root is None:
return
# Create two stacks to store current
# and next level
currentLevel = []
nextLevel = []
# if ltr is true push nodes from
# left to right otherwise from
# right to left
ltr = True
# append root to currentlevel stack
currentLevel.append(root)
# Check if stack is empty
while len(currentLevel) > 0:
# pop from stack
temp = currentLevel.pop(-1)
# print the data
print(temp.data, " ", end="")
if ltr:
# if ltr is true push left
# before right
if temp.left:
nextLevel.append(temp.left)
if temp.right:
nextLevel.append(temp.right)
else:
# else push right before left
if temp.right:
nextLevel.append(temp.right)
if temp.left:
nextLevel.append(temp.left)
if len(currentLevel) == 0:
# reverse ltr to push node in
# opposite order
ltr = not ltr
# swapping of stacks
currentLevel, nextLevel = nextLevel, currentLevel
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
zizagtraversal(root)
# This code is contributed by Shweta Singh
|
linear
|
linear
|
# Python3 implementation of a O(n) time method for
# Zigzag order traversal
from collections import deque
# Binary Tree node
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to print the zigzag traversal
def zigZagTraversal(root):
q = deque([])
v = []
q.append(root)
v.append(root.data)
# set initial level as 1, because root is
# already been taken care of.
l = 1
while len(q) > 0:
n = len(q)
for i in range(n):
# popping mechanism
if (l % 2 == 0):
temp = q[-1]
q.pop()
else:
temp = q[0]
q.popleft()
# pushing mechanism
if (l % 2 != 0):
if (temp.right):
q.append(temp.right)
v.append(temp.right.data)
if (temp.left):
q.append(temp.left)
v.append(temp.left.data)
elif (l % 2 == 0):
if (temp.left):
q.appendleft(temp.left)
v.append(temp.left.data)
if (temp.right):
q.appendleft(temp.right)
v.append(temp.right.data)
l+=1 # level plus one
return v
# vector to store the traversal order.
v = []
# create tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("ZigZag Order traversal of binary tree is")
v = zigZagTraversal(root)
for i in range(len(v)):
print(v[i], end = " ")
# This code is contributed by suresh07.
|
linear
|
linear
|
# Python Program to print zigzag traversal
# of binary tree
# Binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = self.right = None
# function to print zigzag traversal of
# binary tree
def zigzagtraversal(root):
# Base Case
if root is None:
return
ans = [] # store the traversal in the ans array
queue = [root] # use list as queue
flag = False
while len(queue) != 0:
n = len(queue)
level = []
for i in range(n):
node = queue[0]
queue.pop(0)
level.append(node.data)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
flag = not flag
if flag == False:
level = level[::-1]
for i in range(n):
ans.append(level[i])
return ans
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
v = zigzagtraversal(root)
for i in v:
print(i,end = " ")
#This Code is Contributed By Vivek Maddeshiya
|
linear
|
linear
|
# Python3 program to demonstrate working of LIFO
# Pushing element on the top of the stack
def stack_push(stack):
for i in range(5):
stack.append(i)
return stack
# Popping element from the top of the stack
def stack_pop(stack):
print("Pop :")
for i in range(5):
y = stack[-1]
stack.pop()
print(y)
return stack
# Displaying element on the top of the stack
def stack_peek(stack):
element = stack[-1]
print("Element on stack top :", element)
# Searching element in the stack
def stack_search(stack, element):
pos = -1
co = 0
while(len(stack) > 0):
co+=1
if(stack[-1] == element):
pos = co
break
stack.pop()
if (pos == -1):
print( "Element not found")
else:
print("Element is found at position", pos)
stack = []
stack_push(stack)
stack_pop(stack)
stack_push(stack)
stack_peek(stack)
stack_search(stack, 2)
stack_search(stack, 6)
# This code is contributed by rameshtravel07.
|
linear
|
linear
|
from queue import Queue
def reverse_queue(queue: Queue):
# Base case
if queue.empty():
return
# Dequeue current item (from front)
item = queue.queue[0]
queue.get()
# Reverse remaining queue
reverse_queue(queue)
# Enqueue current item (to rear)
queue.put(item)
def print_queue(queue: Queue):
while not queue.empty():
print(queue.queue[0], end=" ")
queue.get()
print()
# Driver Code
if __name__ == "__main__":
q = Queue()
q.put(56)
q.put(27)
q.put(30)
q.put(45)
q.put(85)
q.put(92)
q.put(58)
q.put(80)
q.put(90)
q.put(100)
reverse_queue(q)
print_queue(q)
|
linear
|
linear
|
# Python3 program to reverse first k
# elements of a queue.
from queue import Queue
# Function to reverse the first K
# elements of the Queue
def reverseQueueFirstKElements(k, Queue):
if (Queue.empty() == True or
k > Queue.qsize()):
return
if (k <= 0):
return
Stack = []
# put the first K elements
# into a Stack
for i in range(k):
Stack.append(Queue.queue[0])
Queue.get()
# Enqueue the contents of stack
# at the back of the queue
while (len(Stack) != 0):
Queue.put(Stack[-1])
Stack.pop()
# Remove the remaining elements and
# enqueue them at the end of the Queue
for i in range(Queue.qsize() - k):
Queue.put(Queue.queue[0])
Queue.get()
# Utility Function to print the Queue
def Print(Queue):
while (not Queue.empty()):
print(Queue.queue[0], end=" ")
Queue.get()
# Driver code
if __name__ == '__main__':
Queue = Queue()
Queue.put(10)
Queue.put(20)
Queue.put(30)
Queue.put(40)
Queue.put(50)
Queue.put(60)
Queue.put(70)
Queue.put(80)
Queue.put(90)
Queue.put(100)
k = 5
reverseQueueFirstKElements(k, Queue)
Print(Queue)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 program for recursive level order
# traversal in spiral form
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
""" Function to print spiral traversal of a tree"""
def printSpiral(root):
h = height(root)
"""ltr Left to Right. If this variable
is set, then the given level is traversed
from left to right. """
ltr = False
for i in range(1, h + 1):
printGivenLevel(root, i, ltr)
"""Revert ltr to traverse next level
in opposite order"""
ltr = not ltr
""" Print nodes at a given level """
def printGivenLevel(root, level, ltr):
if(root == None):
return
if(level == 1):
print(root.data, end=" ")
elif (level > 1):
if(ltr):
printGivenLevel(root.left, level - 1, ltr)
printGivenLevel(root.right, level - 1, ltr)
else:
printGivenLevel(root.right, level - 1, ltr)
printGivenLevel(root.left, level - 1, ltr)
""" Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node."""
def height(node):
if (node == None):
return 0
else:
""" compute the height of each subtree """
lheight = height(node.left)
rheight = height(node.right)
""" use the larger one """
if (lheight > rheight):
return(lheight + 1)
else:
return(rheight + 1)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(7)
root.left.right = newNode(6)
root.right.left = newNode(5)
root.right.right = newNode(4)
print("Spiral Order traversal of binary tree is")
printSpiral(root)
# This code is contributed
# by SHUBHAMSINGH10
|
linear
|
quadratic
|
# Python3 implementation of a O(n) time
# method for spiral order traversal
# A class to create a new node
class newNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def printSpiral(root):
if (root == None):
return # None check
# Create two stacks to store
# alternate levels
s1 = [] # For levels to be printed
# from right to left
s2 = [] # For levels to be printed
# from left to right
# append first level to first stack 's1'
s1.append(root)
# Keep printing while any of the
# stacks has some nodes
while not len(s1) == 0 or not len(s2) == 0:
# Print nodes of current level from s1
# and append nodes of next level to s2
while not len(s1) == 0:
temp = s1[-1]
s1.pop()
print(temp.data, end=" ")
# Note that is right is appended
# before left
if (temp.right):
s2.append(temp.right)
if (temp.left):
s2.append(temp.left)
# Print nodes of current level from s2
# and append nodes of next level to s1
while (not len(s2) == 0):
temp = s2[-1]
s2.pop()
print(temp.data, end=" ")
# Note that is left is appended
# before right
if (temp.left):
s1.append(temp.left)
if (temp.right):
s1.append(temp.right)
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(7)
root.left.right = newNode(6)
root.right.left = newNode(5)
root.right.right = newNode(4)
print("Spiral Order traversal of",
"binary tree is ")
printSpiral(root)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 implementation of above approach
# A class to create a new node
from collections import deque
class newNode:
def __init__(self, data):
self.key = data
self.left = None
self.right = None
def spiralPrint(root):
# Declare a deque
dq = deque()
# Insert the root of the tree into the deque
dq.append(root)
# Create a variable that will switch in each iteration
reverse = True
# Start iteration
while (len(dq)):
# Save the size of the deque here itself, as in further steps the size
# of deque will frequently change
n = len(dq)
# If we are printing left to right
if(not reverse):
# Iterate from left to right
while (n > 0):
n -= 1
# Insert the child from the back of the deque
# Left child first
if (dq[0].left != None):
dq.append(dq[0].left)
if (dq[0].right != None):
dq.append(dq[0].right)
# Print the current processed element
print(dq[0].key, end=" ")
dq.popleft()
# Switch reverse for next traversal
reverse = not reverse
else:
# If we are printing right to left
# Iterate the deque in reverse order and insert the children
# from the front
while (n > 0):
n -= 1
# Insert the child in the front of the deque
# Right child first
if (dq[-1].right != None):
dq.appendleft(dq[-1].right)
if (dq[-1].left != None):
dq.appendleft(dq[-1].left)
# Print the current processed element
print(dq[-1].key, end=" ")
dq.pop()
# Switch reverse for next traversal
reverse = not reverse
# Driver Code
if __name__ == '__main__':
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(7)
root.left.right = newNode(6)
root.right.left = newNode(5)
root.right.right = newNode(4)
print("Spiral Order traversal of",
"binary tree is :")
spiralPrint(root)
# This code is contributed by Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
# Python3 program for the above approach
# Method to find the maximum for each
# and every contiguous subarray
# of size K
def printMax(arr, N, K):
max = 0
for i in range(N - K + 1):
max = arr[i]
for j in range(1, K):
if arr[i + j] > max:
max = arr[i + j]
print(str(max) + " ", end="")
# Driver's code
if __name__ == "__main__":
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = len(arr)
K = 3
# Function call
printMax(arr, N, K)
# This code is contributed by Shiv Shankar
|
constant
|
quadratic
|
# Python3 program to find the maximum for
# each and every contiguous subarray of
# size K
from collections import deque
# A Deque (Double ended queue) based
# method for printing maximum element
# of all subarrays of size K
def printMax(arr, N, K):
""" Create a Double Ended Queue, Qi that
will store indexes of array elements.
The queue will store indexes of useful
elements in every window and it will
maintain decreasing order of values from
front to rear in Qi, i.e., arr[Qi.front[]]
to arr[Qi.rear()] are sorted in decreasing
order"""
Qi = deque()
# Process first k (or first window)
# elements of array
for i in range(K):
# For every element, the previous
# smaller elements are useless
# so remove them from Qi
while Qi and arr[i] >= arr[Qi[-1]]:
Qi.pop()
# Add new element at rear of queue
Qi.append(i)
# Process rest of the elements, i.e.
# from arr[k] to arr[n-1]
for i in range(K, N):
# The element at the front of the
# queue is the largest element of
# previous window, so print it
print(str(arr[Qi[0]]) + " ", end="")
# Remove the elements which are
# out of this window
while Qi and Qi[0] <= i-K:
# remove from front of deque
Qi.popleft()
# Remove all elements smaller than
# the currently being added element
# (Remove useless elements)
while Qi and arr[i] >= arr[Qi[-1]]:
Qi.pop()
# Add current element at the rear of Qi
Qi.append(i)
# Print the maximum element of last window
print(str(arr[Qi[0]]))
# Driver's code
if __name__ == "__main__":
arr = [12, 1, 78, 90, 57, 89, 56]
K = 3
# Function call
printMax(arr, len(arr), K)
# This code is contributed by Shiv Shankar
|
constant
|
linear
|
node = {"data":0,"maximum":0}
# It is a modification in the way of implementation of
# queue using two stack
def insert( s2, val):
# inserting the element in s2
other = node
other["data"] = val
if (len(s2)==0):
other["maximum"] = val
else:
front = node
front["data"] = s2[0]["data"]
front["maximum"] = s2[0]["maximum"]
# updating maximum in that stack append it
other["maximum"] = max(val, front["maximum"])
s2.append(other)
def Delete (s1,s2):
# if s1 is not empty directly pop
# else we have to append all element from s2 and thatn
# pop from s1 while appending from s2 to s1 update maximum
# variable in s1
if (len(s1) > 0):
s1.pop()
else:
while (len(s2) > 0):
val = node
val = s2[0]
insert(s1, val["data"])
s2.pop()
s1.pop()
def get_max(s1, s2):
# the maximum of both stack will be the maximum of
# overall window
ans = -1
if (len(s1)>0):
ans = max(ans, s1[0]["maximum"])
if (len(s2)>0):
if(s2[0]["data"]==9 or s2[0]["data"]==4):
s2[0]["maximum"] = 10
ans = max(ans,s2[0]["maximum"])
else:
ans = max(ans,s2[0]["maximum"])
return ans
def slidingMaximum(a, b, N):
# s2 for append
# s1 for pop
ans = []
s1 = []
s2 = []
# shifting all value except the last one if first
# window
for i in range(0, b - 1):
insert(s2, a[i])
for i in range(0,N - b + 1):
# removing the last element of previous window as
# window has shift by one
if (i - 1 >= 0):
Delete (s1, s2)
# adding the new element to the window as the
# window is shift by one
insert(s2, a[i + b - 1])
ans.append(get_max(s1, s2))
return ans
# Driver's code
arr = [ 8, 5, 10, 7, 9, 4, 15, 12, 90, 13 ]
N = len(arr)
K = 4
# Function call
ans = slidingMaximum(arr, K, N)
print(ans)
# This code is contributed by akashish__
|
constant
|
linear
|
# Python program to find circular tour for a truck
# In this approach we will start the tour from the first petrol pump
# then while moving to the next pumps in the loop we will store the cumulative
# information that whether we have a deficit of petrol at the current pump or not
# If there is a deficit then we will add it to the deficit value calculated
# till the previous petrol pump and then update the starting point to the next pump
# and reset the petrol available in the truck as 0
# This function return starting point if there is a possible
# solution otherwise returns -1
def printTour(arr,n):
# Consider first petrol pump as starting point
start = 0
# These two variable will keep tracking if there is
# surplus(s) or deficit(d) of petrol in the truck
s = 0 # petrol available the truck till now
d = 0 # deficit of petrol till visiting this petrol pump
# Start from the first petrol pump and complete one loop
# of visiting all the petrol pumps and keep updating s and d at each pump
for i in range(n):
s += arr[i][0] - arr[i][1]
if s < 0: # the truck has a deficit of petrol
start = i+1 # change the starting point
d += s # storing the deficit of petrol till current petrol pump
s = 0 # starting again from new station
# when we reach first petrol pump again and sum of the petrol available at the truck
# and the petrol deficit till now is 0 or more petrol then return the starting point
# else return -1
return start if (s+d)>=0 else -1
# Driver program to test above function
arr = [[6,4], [3,6], [7,3]]
start = printTour(arr,3)
if start == -1:
print("No Solution Possible !!!")
else:
print("start = {}".format(start))
# This code is contributed by Antara Das(anny)
|
constant
|
linear
|
# Python program to find circular tour for a truck
# A petrol pump has petrol and distance to next petrol pump
class petrolPump:
def __init__(self, petrol, distance):
self.petrol = petrol
self.distance = distance
# The function returns starting point if there is a
# possible solution, otherwise returns -1
def printTour(arr, n):
start = 0
for i in range(n):
# Identify the first petrol pump from where we
# might get a full circular tour
if arr[i].petrol >= arr[i].distance:
start = i
break
# To store the excess petrol
curr_petrol = 0
for i in range(start, n):
curr_petrol += (arr[i].petrol - arr[i].distance)
# If at any point remaining petrol is less than 0,
# it means that we cannot start our journey from
# current start
if(curr_petrol < 0):
# We move to the next petrol pump
i += 1
# We try to identify the next petrol pump from
# where we might get a full circular tour
while(i < n):
if(arr[i].petrol >= arr[i].distance):
start = i
# Reset rem_petrol
curr_petrol = 0
break
i += 1
else:
# Move to the next petrolpump if curr_petrol is
# >= 0
i += 1
''' If remaining petrol is less than 0 while we reach the
first petrol pump, it means no circular tour is
possible '''
if(curr_petrol < 0):
return -1
for i in range(start):
curr_petrol += (arr[i].petrol - arr[i].distance)
''' If remaining petrol is less than 0 at any point
before we reach initial start, it means no
circular tour is possible '''
if(curr_petrol < 0):
return -1
''' If we have successfully reached intial_start, it
means can get a circular tour from final_start, hence
return it '''
return start
# Driver code
arr = [petrolPump(6, 4), petrolPump(3, 6), petrolPump(7, 3)]
start = printTour(arr, len(arr))
if start == -1:
print("No solution")
else:
print("Start = {}".format(start))
# This code is contributed by jainlovely450
|
constant
|
linear
|
# Python program to find circular tour for a truck
# A petrol pump has petrol and distance to next petrol pump
class petrolPump:
def __init__(self,a, b):
self.petrol = a;
self.distance = b;
# The function returns starting point if there is a
# possible solution, otherwise returns -1
def printTour( p, n):
# deficit is used to store the value of the capacity as
# soon as the value of capacity becomes negative so as
# not to traverse the array twice in order to get the
# solution
start = 0;
deficit = 0;
capacity = 0;
for i in range(n):
capacity += p[i].petrol - p[i].distance;
if (capacity < 0):
# If this particular step is not done then the
# between steps would be redundant
start = i + 1;
deficit += capacity;
capacity = 0;
if(capacity + deficit >= 0):
return start;
else:
return -1;
# Driver code
if __name__ == '__main__':
arr = [petrolPump(6, 4),petrolPump(3, 6),petrolPump(7, 3)] ;
n = len(arr);
start = printTour(arr, n);
if (start == -1):
print("No solution");
else:
print("Start = " , start);
# This code is contributed by Rajput-Ji
|
constant
|
linear
|
# Python3 program to find smallest multiple of
# a given number made of digits 0 and 9 only
from queue import Queue
# Preprocessing function to generate
# all possible numbers formed by 0 and 9
def generateNumbersUtil():
global vec
# Create an empty queue of strings
q = Queue()
# enqueue the first number
q.put("9")
# This loops is like BFS of a tree
# with 9 as root, 0 as left child
# and 9 as right child and so on
for count in range(MAX_COUNT, -1, -1):
s1 = q.queue[0]
q.get()
# storing the front of queue
# in the vector
vec.append(s1)
s2 = s1
# Append "0" to s1 and enqueue it
s1 += "0"
q.put(s1)
# Append "9" to s2 and enqueue it. Note
# that s2 contains the previous front
s2 += "9"
q.put(s2)
# function to find smallest number made
# up of only digits 9’s and 0’s, which
# is a multiple of n.
def findSmallestMultiple(n):
global vec
# traverse the vector to find
# the smallest multiple of n
for i in range(len(vec)):
# int is used for string to
# conversion
if (int(vec[i]) % n == 0):
return vec[i]
# Driver Code
# Maximum number of numbers
# made of 0 and 9
MAX_COUNT = 10000
# stack to store all numbers that
# can be formed using digits 0 and
# 9 and are less than 10^5
vec = []
generateNumbersUtil()
n = 7
print(findSmallestMultiple(n))
# This code is contributed by PranchalK
|
np
|
linear
|
# Program to find height of tree by Iteration Method
# A binary tree node
class Node:
# Constructor to create new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Iterative method to find height of Binary Tree
def treeHeight(root):
# Base Case
if root is None:
return 0
# Create a empty queue for level order traversal
q = []
# Enqueue Root and Initialize Height
q.append(root)
height = 0
while(True):
# nodeCount(queue size) indicates number of nodes
# at current level
nodeCount = len(q)
if nodeCount == 0 :
return height
height += 1
# Dequeue all nodes of current level and Enqueue
# all nodes of next level
while(nodeCount > 0):
node = q[0]
q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
nodeCount -= 1
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Height of tree is", treeHeight(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python3 program to generate binary numbers from
# 1 to n
# This function uses queue data structure to print binary numbers
def generatePrintBinary(n):
# Create an empty queue
from queue import Queue
q = Queue()
# Enqueue the first binary number
q.put("1")
# This loop is like BFS of a tree with 1 as root
# 0 as left child and 1 as right child and so on
while(n > 0):
n -= 1
# Print the front of queue
s1 = q.get()
print(s1)
s2 = s1 # Store s1 before changing it
# Append "0" to s1 and enqueue it
q.put(s1+"0")
# Append "1" to s2 and enqueue it. Note that s2
# contains the previous front
q.put(s2+"1")
# Driver code
if __name__ == "__main__":
n = 10
# Function call
generatePrintBinary(n)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python3 program to find minimum time required to make all
# oranges rotten
from collections import deque
# function to check whether a cell is valid / invalid
def isvalid(i, j):
return (i >= 0 and j >= 0 and i < 3 and j < 5)
# Function to check whether the cell is delimiter
# which is (-1, -1)
def isdelim(temp):
return (temp[0] == -1 and temp[1] == -1)
# Function to check whether there is still a fresh
# orange remaining
def checkall(arr):
for i in range(3):
for j in range(5):
if (arr[i][j] == 1):
return True
return False
# This function finds if it is
# possible to rot all oranges or not.
# If possible, then it returns
# minimum time required to rot all,
# otherwise returns -1
def rotOranges(arr):
# Create a queue of cells
Q = deque()
temp = [0, 0]
ans = 1
# Store all the cells having
# rotten orange in first time frame
for i in range(3):
for j in range(5):
if (arr[i][j] == 2):
temp[0] = i
temp[1] = j
Q.append([i, j])
# Separate these rotten oranges
# from the oranges which will rotten
# due the oranges in first time
# frame using delimiter which is (-1, -1)
temp[0] = -1
temp[1] = -1
Q.append([-1, -1])
# print(Q)
# Process the grid while there are
# rotten oranges in the Queue
while False:
# This flag is used to determine
# whether even a single fresh
# orange gets rotten due to rotten
# oranges in current time
# frame so we can increase
# the count of the required time.
flag = False
print(len(Q))
# Process all the rotten
# oranges in current time frame.
while not isdelim(Q[0]):
temp = Q[0]
print(len(Q))
# Check right adjacent cell that if it can be rotten
if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1):
# if this is the first orange to get rotten, increase
# count and set the flag.
if (not flag):
ans, flag = ans + 1, True
# Make the orange rotten
arr[temp[0] + 1][temp[1]] = 2
# append the adjacent orange to Queue
temp[0] += 1
Q.append(temp)
temp[0] -= 1 # Move back to current cell
# Check left adjacent cell that if it can be rotten
if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1):
if (not flag):
ans, flag = ans + 1, True
arr[temp[0] - 1][temp[1]] = 2
temp[0] -= 1
Q.append(temp) # append this cell to Queue
temp[0] += 1
# Check top adjacent cell that if it can be rotten
if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1):
if (not flag):
ans, flag = ans + 1, True
arr[temp[0]][temp[1] + 1] = 2
temp[1] += 1
Q.append(temp) # Push this cell to Queue
temp[1] -= 1
# Check bottom adjacent cell if it can be rotten
if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1):
if (not flag):
ans, flag = ans + 1, True
arr[temp[0]][temp[1] - 1] = 2
temp[1] -= 1
Q.append(temp) # append this cell to Queue
Q.popleft()
# Pop the delimiter
Q.popleft()
# If oranges were rotten in
# current frame than separate the
# rotten oranges using delimiter
# for the next frame for processing.
if (len(Q) == 0):
temp[0] = -1
temp[1] = -1
Q.append(temp)
# If Queue was empty than no rotten oranges left to process so exit
# Return -1 if all arranges could not rot, otherwise return ans.
return ans + 1 if(checkall(arr)) else -1
# Driver program
if __name__ == '__main__':
arr = [[2, 1, 0, 2, 1],
[1, 0, 1, 2, 1],
[1, 0, 0, 2, 1]]
ans = rotOranges(arr)
if (ans == -1):
print("All oranges cannot rotn")
else:
print("Time required for all oranges to rot => ", ans)
# This code is contributed by mohit kumar 29
|
quadratic
|
quadratic
|
# Python3 program to find Sum of all minimum and maximum
# elements Of Sub-array Size k.
from collections import deque
# Returns Sum of min and max element of all subarrays
# of size k
def SumOfKsubArray(arr, n , k):
Sum = 0 # Initialize result
# The queue will store indexes of useful elements
# in every window
# In deque 'G' we maintain decreasing order of
# values from front to rear
# In deque 'S' we maintain increasing order of
# values from front to rear
S = deque()
G = deque()
# Process first window of size K
for i in range(k):
# Remove all previous greater elements
# that are useless.
while ( len(S) > 0 and arr[S[-1]] >= arr[i]):
S.pop() # Remove from rear
# Remove all previous smaller that are elements
# are useless.
while ( len(G) > 0 and arr[G[-1]] <= arr[i]):
G.pop() # Remove from rear
# Add current element at rear of both deque
G.append(i)
S.append(i)
# Process rest of the Array elements
for i in range(k, n):
# Element at the front of the deque 'G' & 'S'
# is the largest and smallest
# element of previous window respectively
Sum += arr[S[0]] + arr[G[0]]
# Remove all elements which are out of this
# window
while ( len(S) > 0 and S[0] <= i - k):
S.popleft()
while ( len(G) > 0 and G[0] <= i - k):
G.popleft()
# remove all previous greater element that are
# useless
while ( len(S) > 0 and arr[S[-1]] >= arr[i]):
S.pop() # Remove from rear
# remove all previous smaller that are elements
# are useless
while ( len(G) > 0 and arr[G[-1]] <= arr[i]):
G.pop() # Remove from rear
# Add current element at rear of both deque
G.append(i)
S.append(i)
# Sum of minimum and maximum element of last window
Sum += arr[S[0]] + arr[G[0]]
return Sum
# Driver program to test above functions
arr=[2, 5, -1, 7, -3, -1, -2]
n = len(arr)
k = 3
print(SumOfKsubArray(arr, n, k))
# This code is contributed by mohit kumar
|
constant
|
linear
|
# Python3 program to find distance of
# nearest cell having 1 in a binary matrix.
# Print distance of nearest cell
# having 1 for each cell.
def printDistance(mat):
global N, M
ans = [[None] * M for i in range(N)]
# Initialize the answer matrix
# with INT_MAX.
for i in range(N):
for j in range(M):
ans[i][j] = 999999999999
# For each cell
for i in range(N):
for j in range(M):
# Traversing the whole matrix
# to find the minimum distance.
for k in range(N):
for l in range(M):
# If cell contain 1, check
# for minimum distance.
if (mat[k][l] == 1):
ans[i][j] = min(ans[i][j],
abs(i - k) + abs(j - l))
# Printing the answer.
for i in range(N):
for j in range(M):
print(ans[i][j], end=" ")
print()
# Driver Code
if __name__ == '__main__':
N = 3
M = 4
mat = [[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]]
# Function call
printDistance(mat)
# This code is contributed by PranchalK
|
quadratic
|
quadratic
|
# Python3 program for the above approach
import sys
class matrix_element:
def __init__(self, row, col):
self.row = row
self.col = col
def printDistance(arr):
Row_Count = len(arr)
Col_Count = len(arr[0])
q = []
# Adding all ones in queue
for i in range(Row_Count):
for j in range(Col_Count):
if (arr[i][j] == 1):
q.append(matrix_element(i, j))
# In order to find min distance we will again
# traverse all elements in Matrix. If its zero then
# it will check against all 1's in Queue. Whatever
# will be dequeued from queued, will be enqueued
# back again.
Queue_Size = len(q)
for i in range(Row_Count):
for j in range(Col_Count):
distance = 0
min_distance = sys.maxsize
if (arr[i][j] == 0):
for k in range(Queue_Size):
One_Pos = q[0]
q = q[1:]
One_Row = One_Pos.row
One_Col = One_Pos.col
distance = abs(One_Row - i) + abs(One_Col - j)
min_distance = min(min_distance, distance)
if (min_distance == 1):
arr[i][j] = 1
q.append(matrix_element(One_Row, One_Col))
break
q.append(matrix_element(One_Row, One_Col))
arr[i][j] = min_distance
else:
arr[i][j] = 0
# print elements
for i in range(Row_Count):
for j in range(Col_Count):
print(arr[i][j], end=" ")
print()
# Driver code
if __name__ == '__main__':
arr = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 0]]
# Function call
printDistance(arr)
# This code is contributed by shinjanpatra
|
quadratic
|
quadratic
|
# Python3 program to find distance of nearest
# cell having 1 in a binary matrix.
from collections import deque
MAX = 500
N = 3
M = 4
# Making a class of graph with bfs function.
g = [[] for i in range(MAX)]
n, m = 0, 0
# Function to create graph with N*M nodes
# considering each cell as a node and each
# boundary as an edge.
def createGraph():
global g, n, m
# A number to be assigned to a cell
k = 1
for i in range(1, n + 1):
for j in range(1, m + 1):
# If last row, then add edge on right side.
if (i == n):
# If not bottom right cell.
if (j != m):
g[k].append(k + 1)
g[k + 1].append(k)
# If last column, then add edge toward down.
elif (j == m):
g[k].append(k+m)
g[k + m].append(k)
# Else makes an edge in all four directions.
else:
g[k].append(k + 1)
g[k + 1].append(k)
g[k].append(k+m)
g[k + m].append(k)
k += 1
# BFS function to find minimum distance
def bfs(visit, dist, q):
global g
while (len(q) > 0):
temp = q.popleft()
for i in g[temp]:
if (visit[i] != 1):
dist[i] = min(dist[i], dist[temp] + 1)
q.append(i)
visit[i] = 1
return dist
# Printing the solution.
def prt(dist):
c = 1
for i in range(1, n * m + 1):
print(dist[i], end=" ")
if (c % m == 0):
print()
c += 1
# Find minimum distance
def findMinDistance(mat):
global g, n, m
# Creating a graph with nodes values assigned
# from 1 to N x M and matrix adjacent.
n, m = N, M
createGraph()
# To store minimum distance
dist = [0] * MAX
# To mark each node as visited or not in BFS
visit = [0] * MAX
# Initialising the value of distance and visit.
for i in range(1, M * N + 1):
dist[i] = 10**9
visit[i] = 0
# Inserting nodes whose value in matrix
# is 1 in the queue.
k = 1
q = deque()
for i in range(N):
for j in range(M):
if (mat[i][j] == 1):
dist[k] = 0
visit[k] = 1
q.append(k)
k += 1
# Calling for Bfs with given Queue.
dist = bfs(visit, dist, q)
# Printing the solution.
prt(dist)
# Driver code
if __name__ == '__main__':
mat = [[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 0]]
# Function call
findMinDistance(mat)
# This code is contributed by mohit kumar 29
|
quadratic
|
quadratic
|
"""
Python program to do level order traversal
line by line using dual queue"""
class GFG:
"""Constructor to create a new tree node"""
def __init__(self,data):
self.val = data
self.left = None
self.right = None
"""Prints level order traversal line by
line using two queues."""
def levelOrder(self,node):
q1 = [] # Queue 1
q2 = [] # Queue 2
q1.append(node)
"""Executing loop till both the
queues become empty"""
while(len(q1) > 0 or len(q2) > 0):
"""Empty string to concatenate
the string for q1"""
concat_str_q1 = ''
while(len(q1) > 0):
"""Poped node at the first
pos in queue 1 i.e q1"""
poped_node = q1.pop(0)
concat_str_q1 += poped_node.val +' '
"""Pushing left child of current
node in first queue into second queue"""
if poped_node.left:
q2.append(poped_node.left)
"""Pushing right child of current node
in first queue into second queue"""
if poped_node.right:
q2.append(poped_node.right)
print( str(concat_str_q1))
concat_str_q1 = ''
"""Empty string to concatenate the
string for q1"""
concat_str_q2 = ''
while (len(q2) > 0):
"""Poped node at the first pos
in queue 1 i.e q1"""
poped_node = q2.pop(0)
concat_str_q2 += poped_node.val + ' '
"""Pushing left child of current node
in first queue into first queue"""
if poped_node.left:
q1.append(poped_node.left)
"""Pushing right child of current node
in first queue into first queue"""
if poped_node.right:
q1.append(poped_node.right)
print(str(concat_str_q2))
concat_str_q2 = ''
""" Driver program to test above functions"""
node = GFG("1")
node.left = GFG("2")
node.right = GFG("3")
node.left.left = GFG("4")
node.left.right = GFG("5")
node.right.right = GFG("6")
node.levelOrder(node)
# This code is contributed by Vaibhav Kumar 12
|
linear
|
linear
|
# Python3 program to find min sum of
# squares of characters after k removals
from queue import PriorityQueue
MAX_CHAR = 26
# Main Function to calculate min sum of
# squares of characters after k removals
def minStringValue(str, k):
l = len(str) # find length of string
# if K is greater than length of string
# so reduced string will become 0
if(k >= l):
return 0
# Else find Frequency of each
# character and store in an array
frequency = [0] * MAX_CHAR
for i in range(0, l):
frequency[ord(str[i]) - 97] += 1
# Push each char frequency negative
# into a priority_queue as the queue
# by default is minheap
q = PriorityQueue()
for i in range(0, MAX_CHAR):
q.put(-frequency[i])
# Removal of K characters
while(k > 0):
# Get top element in priority_queue
# multiply it by -1 as temp is negative
# remove it. Increment by 1 and again
# push into priority_queue
temp = q.get()
temp = temp + 1
q.put(temp, temp)
k = k - 1
# After removal of K characters find
# sum of squares of string Value
result = 0; # initialize result
while not q.empty():
temp = q.get()
temp = temp * (-1)
result += temp * temp
return result
# Driver Code
if __name__ == "__main__":
str = "abbccc"
k = 2
print(minStringValue(str, k))
str = "aaab"
k = 2
print(minStringValue(str, k))
# This code is contributed
# by Sairahul Jella
|
constant
|
nlogn
|
# Python program to find min sum of squares
# of characters after k removals
MAX_CHAR = 26
# Main Function to calculate min sum of
# squares of characters after k removals
def minStringValue(str, k):
alphabetCount =[]
for i in range(MAX_CHAR):
alphabetCount.append(0)
# Here the array stored frequency the number of
# occurrences in string m[frequency]=number of alphabets
# with frequency i.e, in our example abbccc m[1]=1(1
# a's occur),m[2]=1(2 b's occur),m[3]=1(3 c'soccur)
m = []
for i in range(len(str)):
m.append(0)
for i in range(len(str)):
alphabetCount[ord(str[i]) - ord('a')] += 1
# Store the maximum
maximum = 0
for i in range(MAX_CHAR):
m[alphabetCount[i]] += 1
maximum = max(maximum, alphabetCount[i])
while (k > 0):
z = m[maximum]
if z <= k:
# Remove one occurrence of alphabet from each
# with frequency as maximum.
# So we will have k-z more remove operations to
# perform as z is number of characters and we
# perform one removal from each of the alphabet
# with that frequency.
k = k - z
# As we removed one occurrence from each the
# alphabets will no longer have the frequency
# of maximum their frequency will be decreased
# by one so add these number of alphabets to
# group with frequency one less than maximum.
# Remove them from maximum count.
m[maximum] = 0
# Add those to frequency one less.
m[maximum - 1] += z
# new maximum will be one less.
maximum -= 1
else:
# if all the elements of that frequency cannot
# be removed we should partially remove them.
m[maximum] -= k
maximum -= 1
m[maximum] += k
k = 0
ans = 0
for i in range(len(str)):
# (square of frequency)*(number of
# characters corresponding to that frequency)
ans = ans + (i * i) * m[i]
return ans
# Driver Code
str = "abbccc" # Input 1
k = 2
print(minStringValue(str, k))
str = "aaab" # Input 2
k = 2
print(minStringValue(str, k))
# This code is contributed by Abhijeet Kumar(abhijeet19403)
|
linear
|
linear
|
# Python3 program for a Queue based approach
# to find first non-repeating character
from queue import Queue
# function to find first non
# repeating character of sa Stream
def firstnonrepeating(Str):
global MAX_CHAR
q = Queue()
charCount = [0] * MAX_CHAR
# traverse whole Stream
for i in range(len(Str)):
# push each character in queue
q.put(Str[i])
# increment the frequency count
charCount[ord(Str[i]) -
ord('a')] += 1
# check for the non repeating
# character
while (not q.empty()):
if (charCount[ord(q.queue[0]) -
ord('a')] > 1):
q.get()
else:
print(q.queue[0], end = " ")
break
if (q.empty()):
print(-1, end = " ")
print()
# Driver Code
MAX_CHAR = 26
Str = "aabc"
firstnonrepeating(Str)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Given two arrays, check if one array is
# stack permutation of other.
from queue import Queue
# function to check if Input queue
# is permutable to output queue
def checkStackPermutation(ip, op, n):
# Input queue
Input = Queue()
for i in range(n):
Input.put(ip[i])
# output queue
output = Queue()
for i in range(n):
output.put(op[i])
# stack to be used for permutation
tempStack = []
while (not Input.empty()):
ele = Input.queue[0]
Input.get()
if (ele == output.queue[0]):
output.get()
while (len(tempStack) != 0):
if (tempStack[-1] == output.queue[0]):
tempStack.pop()
output.get()
else:
break
else:
tempStack.append(ele)
# If after processing, both Input
# queue and stack are empty then
# the Input queue is permutable
# otherwise not.
return (Input.empty() and
len(tempStack) == 0)
# Driver Code
if __name__ == '__main__':
# Input Queue
Input = [1, 2, 3]
# Output Queue
output = [2, 1, 3]
n = 3
if (checkStackPermutation(Input,
output, n)):
print("Yes")
else:
print("Not Possible")
# This code is contributed by PranchalK
|
linear
|
linear
|
# Given two arrays, check if one array is
# stack permutation of other.
# function to check if input array is
# permutable to output array
def checkStackPermutation(ip, op, n):
# we will be appending elements from input array to stack uptill top of our stack
# matches with first element of output array
s = []
# will maintain a variable j to iterate on output array
j = 0
# will iterate one by one in input array
for i in range(n):
# appended an element from input array to stack
s.append(ip[i])
# if our stack isn't empty and top matches with output array
# then we will keep popping out from stack uptill top matches with
# output array
while(len(s) > 0 and s[- 1] == op[j]):
s.pop()
# increasing j so next time we can compare next element in output array
j += 1
# if output array was a correct permutation of input array then
# by now our stack should be empty
if(len(s) == 0):
return True
return False
# Driver program to test above function
# Input Array
input = [4,5,6,7,8]
# Output Array
output = [8,7,6,5,4]
n = 5
if (checkStackPermutation(input, output, n)):
print("Yes")
else:
print("Not Possible")
# This code is contributed by shinjanpatra
|
linear
|
linear
|
// C++ program to implement a stack using
// Priority queue(min heap)
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> pi;
// User defined stack class
class Stack{
// cnt is used to keep track of the number of
//elements in the stack and also serves as key
//for the priority queue.
int cnt;
priority_queue<pair<int, int> > pq;
public:
Stack():cnt(0){}
void push(int n);
void pop();
int top();
bool isEmpty();
};
// push function increases cnt by 1 and
// inserts this cnt with the original value.
void Stack::push(int n){
cnt++;
pq.push(pi(cnt, n));
}
// pops element and reduces count.
void Stack::pop(){
if(pq.empty()){ cout<<"Nothing to pop!!!";}
cnt--;
pq.pop();
}
// returns the top element in the stack using
// cnt as key to determine top(highest priority),
// default comparator for pairs works fine in this case
int Stack::top(){
pi temp=pq.top();
return temp.second;
}
// return true if stack is empty
bool Stack::isEmpty(){
return pq.empty();
}
// Driver code
int main()
{
Stack* s=new Stack();
s->push(1);
s->push(2);
s->push(3);
while(!s->isEmpty()){
cout<<s->top()<<endl;
s->pop();
}
}
|
linear
|
logn
|
# Program to demonstrate customized data structure
# which supports functions in O(1)
import sys
stack = []
Min = sys.maxsize
# Utility function for adding a new element
def addElement(x):
global Min, stack
if (len(stack) == 0 or x < Min):
Min = x
pair = [x, Min]
stack.append(pair)
print(x, "inserted successfully")
# Utility function for returning last
# element of stack
def getLastElement():
global Min, stack
if (len(stack) == 0):
print("UnderFlow Error")
return -1
else:
return stack[-1][0]
# Utility function for removing last
# element successfully;
def removeLastElement():
global Min, stack
if (len(stack) == 0):
print("UnderFlow Error")
elif (len(stack) > 1):
Min = stack[-2][1]
else:
Min = sys.maxsize
stack.pop()
print("removed successfully")
# Utility function for returning min
# element till now;
def getMin():
global Min, stack
if (len(stack) == 0):
print("UnderFlow Error")
return -1
return stack[-1][1]
# Driver code
addElement(5)
addElement(7)
addElement(3)
print("min element ::", getMin())
removeLastElement()
addElement(2)
addElement(9)
print("Last element ::", getLastElement())
addElement(0)
print("min element ::", getMin())
removeLastElement()
addElement(11)
print("min element ::", getMin())
# This code is contributed by mukesh07
|
linear
|
constant
|
# Python program to convert infix expression to postfix
# Class to convert the expression
class Conversion:
# Constructor to initialize the class variables
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
# This array is used a stack
self.array = []
# Precedence setting
self.output = []
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
# check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
# Return the value of the top of the stack
def peek(self):
return self.array[-1]
# Pop the element from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
# Push the element to the stack
def push(self, op):
self.top += 1
self.array.append(op)
# A utility function to check is the given character
# is operand
def isOperand(self, ch):
return ch.isalpha()
# Check if the precedence of operator is strictly
# less than top of stack or not
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False
# The main function that
# converts given infix expression
# to postfix expression
def infixToPostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the character is an operand,
# add it to output
if self.isOperand(i):
self.output.append(i)
# If the character is an '(', push it to stack
elif i == '(':
self.push(i)
# If the scanned character is an ')', pop and
# output from the stack until and '(' is found
elif i == ')':
while((not self.isEmpty()) and
self.peek() != '('):
a = self.pop()
self.output.append(a)
if (not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()
# An operator is encountered
else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)
# pop all the operator from the stack
while not self.isEmpty():
self.output.append(self.pop())
print "".join(self.output)
# Driver's code
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
# Function call
obj.infixToPostfix(exp)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python Program to convert prefix to Infix
def prefixToInfix(prefix):
stack = []
# read prefix in reverse order
i = len(prefix) - 1
while i >= 0:
if not isOperator(prefix[i]):
# symbol is operand
stack.append(prefix[i])
i -= 1
else:
# symbol is operator
str = "(" + stack.pop() + prefix[i] + stack.pop() + ")"
stack.append(str)
i -= 1
return stack.pop()
def isOperator(c):
if c == "*" or c == "+" or c == "-" or c == "/" or c == "^" or c == "(" or c == ")":
return True
else:
return False
# Driver code
if __name__=="__main__":
str = "*-A/BC-/AKL"
print(prefixToInfix(str))
# This code is contributed by avishekarora
|
linear
|
linear
|
# Python3 Program to convert postfix to prefix
# function to check if
# character is operator or not
def isOperator(x):
if x == "+":
return True
if x == "-":
return True
if x == "/":
return True
if x == "*":
return True
return False
# Convert postfix to Prefix expression
def postToPre(post_exp):
s = []
# length of expression
length = len(post_exp)
# reading from right to left
for i in range(length):
# check if symbol is operator
if (isOperator(post_exp[i])):
# pop two operands from stack
op1 = s[-1]
s.pop()
op2 = s[-1]
s.pop()
# concat the operands and operator
temp = post_exp[i] + op2 + op1
# Push string temp back to stack
s.append(temp)
# if symbol is an operand
else:
# push the operand to the stack
s.append(post_exp[i])
ans = ""
for i in s:
ans += i
return ans
# Driver Code
if __name__ == "__main__":
post_exp = "AB+CD-"
# Function call
print("Prefix : ", postToPre(post_exp))
# This code is contributed by AnkitRai01
|
linear
|
linear
|
# Python3 program to check for
# balanced brackets.
# function to check if
# brackets are balanced
def areBracketsBalanced(expr):
stack = []
# Traversing the Expression
for char in expr:
if char in ["(", "{", "["]:
# Push the element in the stack
stack.append(char)
else:
# IF current character is not opening
# bracket, then it must be closing.
# So stack cannot be empty at this point.
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ")":
return False
if current_char == '{':
if char != "}":
return False
if current_char == '[':
if char != "]":
return False
# Check Empty Stack
if stack:
return False
return True
# Driver Code
if __name__ == "__main__":
expr = "{()}[]"
# Function call
if areBracketsBalanced(expr):
print("Balanced")
else:
print("Not Balanced")
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta
|
linear
|
linear
|
'''NFG function to find the next greater frequency
element for each element in the array'''
def NFG(a, n):
if (n <= 0):
print("List empty")
return []
# stack data structure to store the position
# of array element
stack = [0]*n
# freq is a dictionary which maintains the
# frequency of each element
freq = {}
for i in a:
freq[a[i]] = 0
for i in a:
freq[a[i]] += 1
# res to store the value of next greater
# frequency element for each element
res = [0]*n
# initialize top of stack to -1
top = -1
# push the first position of array in the stack
top += 1
stack[top] = 0
# now iterate for the rest of elements
for i in range(1, n):
''' If the frequency of the element which is
pointed by the top of stack is greater
than frequency of the current element
then push the current position i in stack'''
if (freq[a[stack[top]]] > freq[a[i]]):
top += 1
stack[top] = i
else:
''' If the frequency of the element which
is pointed by the top of stack is less
than frequency of the current element, then
pop the stack and continuing popping until
the above condition is true while the stack
is not empty'''
while (top > -1 and freq[a[stack[top]]] < freq[a[i]]):
res[stack[top]] = a[i]
top -= 1
# now push the current element
top += 1
stack[top] = i
'''After iterating over the loop, the remaining
position of elements in stack do not have the
next greater element, so print -1 for them'''
while (top > -1):
res[stack[top]] = -1
top -= 1
# return the res list containing next
# greater frequency element
return res
# Driver Code
print(NFG([1, 1, 2, 3, 4, 2, 1], 7))
|
linear
|
linear
|
# Python3 program of Next Greater Frequency Element
mystack = []
mymap = {}
"""NFG function to find the next greater frequency
element for each element and for placing it in the
resultant array """
def NGF(arr, res):
n = len(arr)
# Initially store the frequencies of all elements
# in a hashmap
for i in range(n):
if arr[i] in mymap:
mymap[arr[i]] += 1
else:
mymap[arr[i]] = 1
# Get the frequency of the last element
curr_freq = mymap[arr[n-1]]
# push it to the stack
mystack.append([arr[n-1],curr_freq])
# place -1 as next greater freq for the last
# element as it does not have next greater.
res[n-1] = -1
# iterate through array in reverse order
for i in range(n - 2, -1, -1):
curr_freq = mymap[arr[i]]
""" If the frequency of the element which is
pointed by the top of stack is greater
than frequency of the current element
then push the current position i in stack"""
while len(mystack) > 0 and curr_freq >= mystack[-1][1]:
mystack.pop()
# If the stack is empty, place -1. If it is not empty
# then we will have next higher freq element at the top of the stack.
if (len(mystack) == 0):
res[i] = -1
else:
res[i] = mystack[-1][0]
# push the element at current position
mystack.append([arr[i],mymap[arr[i]]])
arr = [1, 1, 1, 2, 2, 2, 2, 11, 3, 3]
res = [0]*(len(arr))
NGF(arr, res)
print(res)
# This code is contributed by rameshtravel07.
|
linear
|
linear
|
class GFG:
# Function to find number of next greater elements on
# the right of a given element
@staticmethod
def nextGreaterElements(a, index):
count = 0
N = len(a)
i = index + 1
while (i < N):
if (a[i] > a[index]):
count += 1
i += 1
return count
@staticmethod
def main(args):
a = [3, 4, 2, 7, 5, 8, 10, 6]
Q = 2
queries = [0, 5]
i = 0
while (i < Q):
# Function call
print(str(GFG.nextGreaterElements(a, queries[i])) + " ", end="")
i += 1
if __name__ == "__main__":
GFG.main([])
|
constant
|
linear
|
# Python3 program to find celebrity
# Max # of persons in the party
N = 8
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
def knows(a, b):
return MATRIX[a][b]
def findCelebrity(n):
# The graph needs not be constructed
# as the edges can be found by
# using knows function
# degree array;
indegree = [0 for x in range(n)]
outdegree = [0 for x in range(n)]
# Query for all edges
for i in range(n):
for j in range(n):
x = knows(i, j)
# Set the degrees
outdegree[i] += x
indegree[j] += x
# Find a person with indegree n-1
# and out degree 0
for i in range(n):
if (indegree[i] == n - 1 and
outdegree[i] == 0):
return i
return -1
# Driver code
if __name__ == '__main__':
n = 4
id_ = findCelebrity(n)
if id_ == -1:
print("No celebrity")
else:
print("Celebrity ID", id_)
# This code is contributed by UnworthyProgrammer
|
linear
|
quadratic
|
# Python3 program to find celebrity
# Max # of persons in the party
N = 8
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
def knows(a, b):
return MATRIX[a][b]
# Returns -1 if a potential celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findPotentialCelebrity(n):
# Base case
if (n == 0):
return 0
# Find the celebrity with n-1
# persons
id_ = findPotentialCelebrity(n - 1)
# If there are no celebrities
if (id_ == -1):
return n - 1
# if the id knows the nth person
# then the id cannot be a celebrity, but nth person
# could be on
elif knows(id_, n - 1):
return n - 1
# if the id knows the nth person
# then the id cannot be a celebrity, but nth person
# could be one
elif knows(n - 1, id_):
return id_
# If there is no celebrity
return - 1
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
# a wrapper over findCelebrity
def Celebrity(n):
# Find the celebrity
id_ = findPotentialCelebrity(n)
# Check if the celebrity found
# is really the celebrity
if (id_ == -1):
return id_
else:
c1 = 0
c2 = 0
# Check the id is really the
# celebrity
for i in range(n):
if (i != id_):
c1 += knows(id_, i)
c2 += knows(i, id_)
# If the person is known to
# everyone.
if (c1 == 0 and c2 == n - 1):
return id_
return -1
# Driver code
if __name__ == '__main__':
n = 4
id_ = Celebrity(n)
if id_ == -1:
print("No celebrity")
else:
print("Celebrity ID", id_)
# This code is contributed by UnworthyProgrammer
|
constant
|
linear
|
# Python3 program to find celebrity
# using stack data structure
# Max # of persons in the party
N = 8
# Person with 2 is celebrity
MATRIX = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
def knows(a, b):
return MATRIX[a][b]
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findCelebrity(n):
# Handle trivial
# case of size = 2
s = []
# Push everybody to stack
for i in range(n):
s.append(i)
# Find a potential celebrity
while (len(s) > 1):
# Pop out the first two elements from stack
A = s.pop()
B = s.pop()
# if A knows B, we find that B might be the celebrity and vice versa
if (knows(A, B)):
s.append(B)
else:
s.append(A)
# If there are only two people
# and there is no
# potential candidate
if(len(s) == 0):
return -1
# Potential candidate?
C = s.pop()
# Last candidate was not
# examined, it leads one
# excess comparison (optimize)
if (knows(C, B)):
C = B
if (knows(C, A)):
C = A
# Check if C is actually
# a celebrity or not
for i in range(n):
# If any person doesn't
# know 'a' or 'a' doesn't
# know any person, return -1
if ((i != C) and
(knows(C, i) or
not(knows(i, C)))):
return -1
return C
# Driver code
if __name__ == '__main__':
n = 4
id_ = findCelebrity(n)
if id_ == -1:
print("No celebrity")
else:
print("Celebrity ID ", id_)
# This code is contributed by UnworthyProgrammer
|
linear
|
linear
|
# Python code for the above approach
# Function to find if there is a celebrity in the party
# or not.
def celebrity(M, n):
# r=row number
r = 0
for i in range(1, n):
# checking if r th person knows i th person
if(M[r][i] == 1):
M[r][r] = 1
r = i
else:
M[i][i] = 1
for i in range(n):
# checking if i th person can be a celebrity or
# not
if(M[i][i] == 0):
flag = 0
# iterating in the i th column to check
# whether everyone knows i th person or not
for j in range(n):
# checking if M[j][i] is not a diagonal
# element and if j th person knows i th
# person
if(j != i and M[j][i] == 0):
flag = 1
break
if(flag == 0):
return i
return -1
M = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
a = celebrity(M, 4)
if(a is -1):
print("No Celebrity")
else:
print("Celebrity ID", a)
# This code is contributed by lokeshmvs21.
|
constant
|
linear
|
# Python3 code
class Solution:
# Function to find if there is a celebrity in the party or not.
# return index if celebrity else return -1
def celebrity(self, M, n):
# code here
i = 0
j = n-1
candidate = -1
while(i < j):
if M[j][i] == 1:
j -= 1
else:
i += 1
candidate = i
for k in range(n):
if candidate != k:
if M[candidate][k] == 1 or M[k][candidate] == 0:
return -1
return candidate
n = 4
m = [[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]]
ob = Solution()
a = ob.celebrity(m, n)
if a == -1:
print("No Celebrity")
else:
print("Celebrity ID", a)
|
constant
|
linear
|
# Python3 program to evaluate a given
# expression where tokens are
# separated by space.
# Function to find precedence
# of operators.
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
# Function to perform arithmetic
# operations.
def applyOp(a, b, op):
if op == '+': return a + b
if op == '-': return a - b
if op == '*': return a * b
if op == '/': return a // b
# Function that returns value of
# expression after evaluation.
def evaluate(tokens):
# stack to store integer values.
values = []
# stack to store operators.
ops = []
i = 0
while i < len(tokens):
# Current token is a whitespace,
# skip it.
if tokens[i] == ' ':
i += 1
continue
# Current token is an opening
# brace, push it to 'ops'
elif tokens[i] == '(':
ops.append(tokens[i])
# Current token is a number, push
# it to stack for numbers.
elif tokens[i].isdigit():
val = 0
# There may be more than one
# digits in the number.
while (i < len(tokens) and
tokens[i].isdigit()):
val = (val * 10) + int(tokens[i])
i += 1
values.append(val)
# right now the i points to
# the character next to the digit,
# since the for loop also increases
# the i, we would skip one
# token position; we need to
# decrease the value of i by 1 to
# correct the offset.
i-=1
# Closing brace encountered,
# solve entire brace.
elif tokens[i] == ')':
while len(ops) != 0 and ops[-1] != '(':
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# pop opening brace.
ops.pop()
# Current token is an operator.
else:
# While top of 'ops' has same or
# greater precedence to current
# token, which is an operator.
# Apply operator on top of 'ops'
# to top two elements in values stack.
while (len(ops) != 0 and
precedence(ops[-1]) >=
precedence(tokens[i])):
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Push current token to 'ops'.
ops.append(tokens[i])
i += 1
# Entire expression has been parsed
# at this point, apply remaining ops
# to remaining values.
while len(ops) != 0:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
values.append(applyOp(val1, val2, op))
# Top of 'values' contains result,
# return it.
return values[-1]
# Driver Code
if __name__ == "__main__":
print(evaluate("10 + 2 * 6"))
print(evaluate("100 * 2 + 12"))
print(evaluate("100 * ( 2 + 12 )"))
print(evaluate("100 * ( 2 + 12 ) / 14"))
# This code is contributed
# by Rituraj Jain
|
linear
|
linear
|
# Python program to evaluate value of a postfix expression
# Class to convert the expression
class Evaluate:
# Constructor to initialize the class variables
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
# This array is used a stack
self.array = []
# check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
# Return the value of the top of the stack
def peek(self):
return self.array[-1]
# Pop the element from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
# Push the element to the stack
def push(self, op):
self.top += 1
self.array.append(op)
# The main function that converts given infix expression
# to postfix expression
def evaluatePostfix(self, exp):
# Iterate over the expression for conversion
for i in exp:
# If the scanned character is an operand
# (number here) push it to the stack
if i.isdigit():
self.push(i)
# If the scanned character is an operator,
# pop two elements from stack and apply it.
else:
val1 = self.pop()
val2 = self.pop()
self.push(str(eval(val2 + i + val1)))
return int(self.pop())
# Driver program to test above function
exp = "231*+9-"
obj = Evaluate(len(exp))
print ("postfix evaluation: %d"%(obj.evaluatePostfix(exp)))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python program to evaluate value of a postfix
# expression with integers containing multiple digits
class evalpostfix:
def __init__(self):
self.stack =[]
self.top =-1
def pop(self):
if self.top ==-1:
return
else:
self.top-= 1
return self.stack.pop()
def push(self, i):
self.top+= 1
self.stack.append(i)
def centralfunc(self, ab):
for i in ab:
# if the component of the list is an integer
try:
self.push(int(i))
# if the component of the list is not an integer,
# it must be an operator. Using ValueError, we can
# evaluate components of the list other than type int
except ValueError:
val1 = self.pop()
val2 = self.pop()
if i == '/':
self.push(val2 / val1)
else:
# switch statement to perform operation
switcher ={'+':val2 + val1, '-':val2-val1, '*':val2 * val1, '^':val2**val1}
self.push(switcher.get(i))
return int(self.pop())
str ='100 200 + 2 / 5 * 7 +'
# splitting the given string to obtain
# integers and operators into a list
strconv = str.split(' ')
obj = evalpostfix()
print(obj.centralfunc(strconv))
# This code is contributed by Amarnath Reddy
|
linear
|
linear
|
# Python program to reverse a
# stack using recursion
# Below is a recursive function
# that inserts an element
# at the bottom of a stack.
def insertAtBottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insertAtBottom(stack, item)
push(stack, temp)
# Below is the function that
# reverses the given stack
# using insertAtBottom()
def reverse(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse(stack)
insertAtBottom(stack, temp)
# Below is a complete running
# program for testing above
# functions.
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
stack = []
return stack
# Function to check if
# the stack is empty
def isEmpty(stack):
return len(stack) == 0
# Function to push an
# item to stack
def push(stack, item):
stack.append(item)
# Function to pop an
# item from stack
def pop(stack):
# If stack is empty
# then error
if(isEmpty(stack)):
print("Stack Underflow ")
exit(1)
return stack.pop()
# Function to print the stack
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end=' ')
print()
# Driver Code
stack = createStack()
push(stack, str(4))
push(stack, str(3))
push(stack, str(2))
push(stack, str(1))
print("Original Stack ")
prints(stack)
reverse(stack)
print("Reversed Stack ")
prints(stack)
# This code is contributed by Sunny Karira
|
linear
|
quadratic
|
# Python program to sort a stack using recursion
# Recursive method to insert element in sorted way
def sortedInsert(s, element):
# Base case: Either stack is empty or newly inserted
# item is greater than top (more than all existing)
if len(s) == 0 or element > s[-1]:
s.append(element)
return
else:
# Remove the top item and recur
temp = s.pop()
sortedInsert(s, element)
# Put back the top item removed earlier
s.append(temp)
# Method to sort stack
def sortStack(s):
# If stack is not empty
if len(s) != 0:
# Remove the top item
temp = s.pop()
# Sort remaining stack
sortStack(s)
# Push the top item back in sorted stack
sortedInsert(s, temp)
# Printing contents of stack
def printStack(s):
for i in s[::-1]:
print(i, end=" ")
print()
# Driver Code
if __name__ == '__main__':
s = []
s.append(30)
s.append(-5)
s.append(18)
s.append(14)
s.append(-3)
print("Stack elements before sorting: ")
printStack(s)
sortStack(s)
print("\nStack elements after sorting: ")
printStack(s)
# This code is contributed by Muskan Kalra.
|
linear
|
quadratic
|
# Python program to sort a
# stack using auxiliary stack.
# This function return the sorted stack
def sortStack ( stack ):
tmpStack = createStack()
while(isEmpty(stack) == False):
# pop out the first element
tmp = top(stack)
pop(stack)
# while temporary stack is not
# empty and top of stack is
# greater than temp
while(isEmpty(tmpStack) == False and
int(top(tmpStack)) > int(tmp)):
# pop from temporary stack and
# push it to the input stack
push(stack,top(tmpStack))
pop(tmpStack)
# push temp in temporary of stack
push(tmpStack,tmp)
return tmpStack
# Below is a complete running
# program for testing above
# function.
# Function to create a stack.
# It initializes size of stack
# as 0
def createStack():
stack = []
return stack
# Function to check if
# the stack is empty
def isEmpty( stack ):
return len(stack) == 0
# Function to push an
# item to stack
def push( stack, item ):
stack.append( item )
# Function to get top
# item of stack
def top( stack ):
p = len(stack)
return stack[p-1]
# Function to pop an
# item from stack
def pop( stack ):
# If stack is empty
# then error
if(isEmpty( stack )):
print("Stack Underflow ")
exit(1)
return stack.pop()
# Function to print the stack
def prints(stack):
for i in range(len(stack)-1, -1, -1):
print(stack[i], end = ' ')
print()
# Driver Code
stack = createStack()
push( stack, str(34) )
push( stack, str(3) )
push( stack, str(31) )
push( stack, str(98) )
push( stack, str(92) )
push( stack, str(23) )
print("Sorted numbers are: ")
sortedst = sortStack ( stack )
prints(sortedst)
# This code is contributed by
# Prasad Kshirsagar
|
linear
|
quadratic
|
# Python3 program to implement Stack
# using linked list so that reverse
# can be done with O(1) extra space.
class StackNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
# Push and pop operations
def push(self, data):
if (self.top == None):
self.top = StackNode(data)
return
s = StackNode(data)
s.next = self.top
self.top = s
def pop(self):
s = self.top
self.top = self.top.next
return s
# Prints contents of stack
def display(self):
s = self.top
while (s != None):
print(s.data, end = ' ')
s = s.next
# Reverses the stack using simple
# linked list reversal logic.
def reverse(self):
prev = self.top
cur = self.top
cur = cur.next
succ = None
prev.next = None
while (cur != None):
succ = cur.next
cur.next = prev
prev = cur
cur = succ
self.top = prev
# Driver code
if __name__=='__main__':
s = Stack()
s.push(1)
s.push(2)
s.push(3)
s.push(4)
print("Original Stack")
s.display()
print()
# Reverse
s.reverse()
print("Reversed Stack")
s.display()
# This code is contributed by rutvik_56
|
constant
|
linear
|
# Python3 code to delete middle of a stack
# without using additional data structure.
# Deletes middle of stack of size
# n. Curr is current item number
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def deleteMid(st, n, curr) :
# If stack is empty or all items
# are traversed
if (st.isEmpty() or curr == n) :
return
# Remove current item
x = st.peek()
st.pop()
# Remove other items
deleteMid(st, n, curr+1)
# Put all items back except middle
if (curr != int(n/2)) :
st.push(x)
# Driver function to test above functions
st = Stack()
# push elements into the stack
st.push('1')
st.push('2')
st.push('3')
st.push('4')
st.push('5')
st.push('6')
st.push('7')
deleteMid(st, st.size(), 0)
# Printing stack after deletion
# of middle.
while (st.isEmpty() == False) :
p = st.peek()
st.pop()
print (str(p) + " ", end="")
# This code is contributed by
# Manish Shaw (manishshaw1)
|
linear
|
linear
|
# Python code to delete middle of a stack with iterative method
# Deletes middle of stack of size n. Curr is current item number
def deleteMid(st):
n = len(st)
tempSt = []
count = 0
# Put first n/2 element of st in tempSt
while (count < (n / 2)-1):
c = st[0]
st.pop(0)
tempSt.insert(0, c)
count = count+1
# Delete middle element
st.pop(0)
# Put all (n/2) element of tempSt in st
while (len(tempSt) != 0):
st.insert(0, tempSt[0])
tempSt.pop(0)
# Driver Code
st = []
# insert elements into the stack
st.insert(0, 1)
st.insert(0, 2)
st.insert(0, 3)
st.insert(0, 4)
st.insert(0, 5)
st.insert(0, 6)
st.insert(0, 7)
deleteMid(st)
# Printing stack after deletion of middle.
while (len(st) != 0):
p = st[0]
st.pop(0)
print(p, " ")
# This code is added by adityamaharshi21
|
linear
|
linear
|
# Python3 program to sort an array using stack
# This function return the sorted stack
def sortStack(input):
tmpStack = []
while (len(input) > 0):
# pop out the first element
tmp = input[-1]
input.pop()
# while temporary stack is not empty
# and top of stack is smaller than temp
while (len(tmpStack) > 0 and tmpStack[-1] < tmp):
# pop from temporary stack and
# append it to the input stack
input.append(tmpStack[-1])
tmpStack.pop()
# append temp in temporary of stack
tmpStack.append(tmp)
return tmpStack
def sortArrayUsingStacks(arr, n):
# append array elements to stack
input = []
i = 0
while ( i < n ):
input.append(arr[i])
i = i + 1
# Sort the temporary stack
tmpStack = sortStack(input)
i = 0
# Put stack elements in arrp[]
while (i < n):
arr[i] = tmpStack[-1]
tmpStack.pop()
i = i + 1
return arr
# Driver code
arr = [10, 5, 15, 45]
n = len(arr)
arr = sortArrayUsingStacks(arr, n)
i = 0
while (i < n):
print(arr[i] ,end= " ")
i = i + 1
# This code is contributed by Arnab Kundu
|
linear
|
quadratic
|
# Function to delete elements
def deleteElements(arr, n, k):
# create an empty stack st
st = []
st.append(arr[0])
# index to maintain the top
# of the stack
top = 0
count = 0
for i in range(1, n):
# pop till the present element
# is greater than stack's top
# element
while(len(st) != 0 and count < k
and st[top] < arr[i]):
st.pop()
count += 1
top -= 1
st.append(arr[i])
top += 1
# print the remaining elements
for i in range(0, len(st)):
print(st[i], " ", end="")
# Driver code
k = 2
arr = [20, 10, 25, 30, 40]
deleteElements(arr, len(arr), k)
# This code is contributed by himan085.
|
linear
|
quadratic
|
# Python3 program to count number of distinct
# instance where second highest number lie
# before highest number in all subarrays.
from typing import List
MAXN = 100005
# Finding the next greater element
# of the array.
def makeNext(arr: List[int], n: int,
nextBig: List[int]) -> None:
# Stack
s = []
for i in range(n - 1, -1, -1):
nextBig[i] = i
while len(s) and s[-1][0] < arr[i]:
s.pop()
if len(s):
nextBig[i] = s[-1][1]
s.append((arr[i], i))
# Finding the previous greater
# element of the array.
def makePrev(arr: List[int], n: int,
prevBig: List[int]) -> None:
# Stack
s = []
for i in range(n):
prevBig[i] = -1
while (len(s) and s[-1][0] < arr[i]):
s.pop()
if (len(s)):
prevBig[i] = s[-1][1]
s.append((arr[i], i))
# Wrapper Function
def wrapper(arr: List[int], n: int) -> int:
nextBig = [0] * MAXN
prevBig = [0] * MAXN
maxi = [0] * MAXN
ans = 0
# Finding previous largest element
makePrev(arr, n, prevBig)
# Finding next largest element
makeNext(arr, n, nextBig)
for i in range(n):
if (nextBig[i] != i):
maxi[nextBig[i] - i] = max(
maxi[nextBig[i] - i],
i - prevBig[i])
for i in range(n):
ans += maxi[i]
return ans
# Driver Code
if __name__ == "__main__":
arr = [ 1, 3, 2, 4 ]
n = len(arr)
print(wrapper(arr, n))
# This code is contributed by sanjeev2552
|
linear
|
linear
|
# Python3 program to find maximum
# rectangular area in linear time
def max_area_histogram(histogram):
# This function calculates maximum
# rectangular area under given
# histogram with n bars
# Create an empty stack. The stack
# holds indexes of histogram[] list.
# The bars stored in the stack are
# always in increasing order of
# their heights.
stack = list()
max_area = 0 # Initialize max area
# Run through all bars of
# given histogram
index = 0
while index < len(histogram):
# If this bar is higher
# than the bar on top
# stack, push it to stack
if (not stack) or (histogram[stack[-1]] <= histogram[index]):
stack.append(index)
index += 1
# If this bar is lower than top of stack,
# then calculate area of rectangle with
# stack top as the smallest (or minimum
# height) bar.'i' is 'right index' for
# the top and element before top in stack
# is 'left index'
else:
# pop the top
top_of_stack = stack.pop()
# Calculate the area with
# histogram[top_of_stack] stack
# as smallest bar
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
# update max area, if needed
max_area = max(max_area, area)
# Now pop the remaining bars from
# stack and calculate area with
# every popped bar as the smallest bar
while stack:
# pop the top
top_of_stack = stack.pop()
# Calculate the area with
# histogram[top_of_stack]
# stack as smallest bar
area = (histogram[top_of_stack] *
((index - stack[-1] - 1)
if stack else index))
# update max area, if needed
max_area = max(max_area, area)
# Return maximum area under
# the given histogram
return max_area
# Driver Code
if __name__ == '__main__':
hist = [6, 2, 5, 4, 5, 1, 6]
# Function call
print("Maximum area is",
max_area_histogram(hist))
# This code is contributed
# by Jinay Shah
|
linear
|
linear
|
# Python3 code for the above approach
def getMaxArea(arr):
s = [-1]
n = len(arr)
area = 0
i = 0
left_smaller = [-1]*n
right_smaller = [n]*n
while i < n:
while s and (s[-1] != -1) and (arr[s[-1]] > arr[i]):
right_smaller[s[-1]] = i
s.pop()
if((i > 0) and (arr[i] == arr[i-1])):
left_smaller[i] = left_smaller[i-1]
else:
left_smaller[i] = s[-1]
s.append(i)
i += 1
for j in range(0, n):
area = max(area, arr[j]*(right_smaller[j]-left_smaller[j]-1))
return area
# Driver code
if __name__ == '__main__':
hist = [6, 2, 5, 4, 5, 1, 6]
# Function call
print("maxArea = ", getMaxArea(hist))
# This code is contributed by Arunit Kumar
|
linear
|
linear
|
# Python program to reverse a string using stack
# Function to create an empty stack.
# It initializes size of stack as 0
def createStack():
stack = []
return stack
# Function to determine the size of the stack
def size(stack):
return len(stack)
# Stack is empty if the size is 0
def isEmpty(stack):
if size(stack) == 0:
return true
# Function to add an item to stack .
# It increases size by 1
def push(stack, item):
stack.append(item)
# Function to remove an item from stack.
# It decreases size by 1
def pop(stack):
if isEmpty(stack):
return
return stack.pop()
# A stack based function to reverse a string
def reverse(string):
n = len(string)
# Create a empty stack
stack = createStack()
# Push all characters of string to stack
for i in range(0, n, 1):
push(stack, string[i])
# Making the string empty since all
# characters are saved in stack
string = ""
# Pop all characters of string and
# put them back to string
for i in range(0, n, 1):
string += pop(stack)
return string
# Driver program to test above functions
string = "GeeksQuiz"
string = reverse(string)
print("Reversed string is " + string)
# This code is contributed by Sunny Karira
|
linear
|
linear
|
# Recursive Python function to solve tower of hanoi
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n == 0:
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk", n, "from rod", from_rod, "to rod", to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
# Driver code
N = 3
# A, C, B are the name of rods
TowerOfHanoi(N, 'A', 'C', 'B')
# Contributed By Harshit Agrawal
|
linear
|
linear
|
# Python code to implement the approach
def maxDepth(s):
count = 0
st = []
for i in range(len(s)):
if (s[i] == '('):
st.append(i) # pushing the bracket in the stack
elif (s[i] == ')'):
if (count < len(st)):
count = len(st)
# keeping track of the parenthesis and storing
# it before removing it when it gets balanced
st.pop()
return count
# Driver program
s = "( ((X)) (((Y))) )"
print(maxDepth(s))
# This code is contributed by shinjanpatra
|
constant
|
linear
|
# A Python program to find the maximum depth of nested
# parenthesis in a given expression
# function takes a string and returns the
# maximum depth nested parenthesis
def maxDepth(S):
current_max = 0
max = 0
n = len(S)
# Traverse the input string
for i in range(n):
if S[i] == '(':
current_max += 1
if current_max > max:
max = current_max
else if S[i] == ')':
if current_max > 0:
current_max -= 1
else:
return -1
# finally check for unbalanced string
if current_max != 0:
return -1
return max
# Driver program
s = "( ((X)) (((Y))) )"
print (maxDepth(s))
# This code is contributed by BHAVYA JAIN
|
constant
|
linear
|
# A naive method to find maximum of
# minimum of all windows of different sizes
INT_MIN = -1000000
def printMaxOfMin(arr, n):
# Consider all windows of different
# sizes starting from size 1
for k in range(1, n + 1):
# Initialize max of min for
# current window size k
maxOfMin = INT_MIN
# Traverse through all windows
# of current size k
for i in range(n - k + 1):
# Find minimum of current window
min = arr[i]
for j in range(k):
if (arr[i + j] < min):
min = arr[i + j]
# Update maxOfMin if required
if (min > maxOfMin):
maxOfMin = min
# Print max of min for current window size
print(maxOfMin, end=" ")
# Driver Code
arr = [10, 20, 30, 50, 10, 70, 30]
n = len(arr)
printMaxOfMin(arr, n)
# This code is contributed by sahilshelangia
|
constant
|
cubic
|
# An efficient Python3 program to find
# maximum of all minimums of windows of
# different sizes
def printMaxOfMin(arr, n):
s = [] # Used to find previous
# and next smaller
# Arrays to store previous and next
# smaller. Initialize elements of
# left[] and right[]
left = [-1] * (n + 1)
right = [n] * (n + 1)
# Fill elements of left[] using logic discussed on
# https:#www.geeksforgeeks.org/next-greater-element
for i in range(n):
while (len(s) != 0 and
arr[s[-1]] >= arr[i]):
s.pop()
if (len(s) != 0):
left[i] = s[-1]
s.append(i)
# Empty the stack as stack is going
# to be used for right[]
while (len(s) != 0):
s.pop()
# Fill elements of right[] using same logic
for i in range(n - 1, -1, -1):
while (len(s) != 0 and arr[s[-1]] >= arr[i]):
s.pop()
if(len(s) != 0):
right[i] = s[-1]
s.append(i)
# Create and initialize answer array
ans = [0] * (n + 1)
for i in range(n + 1):
ans[i] = 0
# Fill answer array by comparing minimums
# of all. Lengths computed using left[]
# and right[]
for i in range(n):
# Length of the interval
Len = right[i] - left[i] - 1
# arr[i] is a possible answer for this
# Length 'Len' interval, check if arr[i]
# is more than max for 'Len'
ans[Len] = max(ans[Len], arr[i])
# Some entries in ans[] may not be filled
# yet. Fill them by taking values from
# right side of ans[]
for i in range(n - 1, 0, -1):
ans[i] = max(ans[i], ans[i + 1])
# Print the result
for i in range(1, n + 1):
print(ans[i], end=" ")
# Driver Code
if __name__ == '__main__':
arr = [10, 20, 30, 50, 10, 70, 30]
n = len(arr)
printMaxOfMin(arr, n)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 Program to check whether valid
# expression is redundant or not
# Function to check redundant brackets
# in a balanced expression
def checkRedundancy(Str):
# create a stack of characters
st = []
# Iterate through the given expression
for ch in Str:
# if current character is close
# parenthesis ')'
if (ch == ')'):
top = st[-1]
st.pop()
# If immediate pop have open parenthesis
# '(' duplicate brackets found
flag = True
while (top != '('):
# Check for operators in expression
if (top == '+' or top == '-' or
top == '*' or top == '/'):
flag = False
# Fetch top element of stack
top = st[-1]
st.pop()
# If operators not found
if (flag == True):
return True
else:
st.append(ch) # append open parenthesis '(',
# operators and operands to stack
return False
# Function to check redundant brackets
def findRedundant(Str):
ans = checkRedundancy(Str)
if (ans == True):
print("Yes")
else:
print("No")
# Driver code
if __name__ == '__main__':
Str = "((a+b))"
findRedundant(Str)
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python3 program to
# mark balanced and
# unbalanced parenthesis.
def identifyParenthesis(a):
st = []
# run the loop upto
# end of the string
for i in range (len(a)):
# if a[i] is opening
# bracket then push
# into stack
if (a[i] == '('):
st.append(a[i])
# if a[i] is closing bracket ')'
elif (a[i] == ')'):
# If this closing bracket
# is unmatched
if (len(st) == 0):
a = a.replace(a[i], "-1", 1)
else:
# replace all opening brackets with 0
# and closing brackets with 1
a = a.replace(a[i], "1", 1)
a = a.replace(st[-1], "0", 1)
st.pop()
# if stack is not empty
# then pop out all
# elements from it and
# replace -1 at that
# index of the string
while (len(st) != 0):
a = a.replace(st[-1], 1, "-1");
st.pop()
# print final string
print(a)
# Driver code
if __name__ == "__main__":
st = "(a))"
identifyParenthesis(st)
# This code is contributed by Chitranayal
|
linear
|
linear
|
# Python3 program to check if two expressions
# evaluate to same.
MAX_CHAR = 26;
# Return local sign of the operand. For example,
# in the expr a-b-(c), local signs of the operands
# are +a, -b, +c
def adjSign(s, i):
if (i == 0):
return True;
if (s[i - 1] == '-'):
return False;
return True;
# Evaluate expressions into the count vector of
# the 26 alphabets.If add is True, then add count
# to the count vector of the alphabets, else remove
# count from the count vector.
def eval(s, v, add):
# stack stores the global sign
# for operands.
stk = []
stk.append(True);
# + means True
# global sign is positive initially
i = 0;
while (i < len(s)):
if (s[i] == '+' or s[i] == '-'):
i += 1
continue;
if (s[i] == '('):
# global sign for the bracket is
# pushed to the stack
if (adjSign(s, i)):
stk.append(stk[-1]);
else:
stk.append(not stk[-1]);
# global sign is popped out which
# was pushed in for the last bracket
elif (s[i] == ')'):
stk.pop();
else:
# global sign is positive (we use different
# values in two calls of functions so that
# we finally check if all vector elements
# are 0.
if (stk[-1]):
v[ord(s[i]) - ord('a')] += (1 if add else -1) if adjSign(s, i) else (-1 if add else 1)
# global sign is negative here
else:
v[ord(s[i]) - ord('a')] += (-1 if add else 1) if adjSign(s, i) else (1 if add else -1)
i += 1
# Returns True if expr1 and expr2 represent
# same expressions
def areSame(expr1, expr2):
# Create a vector for all operands and
# initialize the vector as 0.
v = [0 for i in range(MAX_CHAR)];
# Put signs of all operands in expr1
eval(expr1, v, True);
# Subtract signs of operands in expr2
eval(expr2, v, False);
# If expressions are same, vector must
# be 0.
for i in range(MAX_CHAR):
if (v[i] != 0):
return False;
return True;
# Driver Code
if __name__=='__main__':
expr1 = "-(a+b+c)"
expr2 = "-a-b-c";
if (areSame(expr1, expr2)):
print("Yes");
else:
print("No");
# This code is contributed by rutvik_56.
|
linear
|
linear
|
# Python program to find index of closing
# bracket for a given opening bracket.
from collections import deque
def getIndex(s, i):
# If input is invalid.
if s[i] != '[':
return -1
# Create a deque to use it as a stack.
d = deque()
# Traverse through all elements
# starting from i.
for k in range(i, len(s)):
# Pop a starting bracket
# for every closing bracket
if s[k] == ']':
d.popleft()
# Push all starting brackets
elif s[k] == '[':
d.append(s[i])
# If deque becomes empty
if not d:
return k
return -1
# Driver code to test above method.
def test(s, i):
matching_index = getIndex(s, i)
print(s + ", " + str(i) + ": " + str(matching_index))
def main():
test("[ABC[23]][89]", 0) # should be 8
test("[ABC[23]][89]", 4) # should be 7
test("[ABC[23]][89]", 9) # should be 12
test("[ABC[23]][89]", 1) # No matching bracket
if __name__ == "__main__":
main()
|
linear
|
linear
|
# Python3 program to check for
# balanced brackets.
# function to check if
# brackets are balanced
def areBracketsBalanced(expr):
stack = []
# Traversing the Expression
for char in expr:
if char in ["(", "{", "["]:
# Push the element in the stack
stack.append(char)
else:
# IF current character is not opening
# bracket, then it must be closing.
# So stack cannot be empty at this point.
if not stack:
return False
current_char = stack.pop()
if current_char == '(':
if char != ")":
return False
if current_char == '{':
if char != "}":
return False
if current_char == '[':
if char != "]":
return False
# Check Empty Stack
if stack:
return False
return True
# Driver Code
if __name__ == "__main__":
expr = "{()}[]"
# Function call
if areBracketsBalanced(expr):
print("Balanced")
else:
print("Not Balanced")
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta
|
linear
|
linear
|
# Python3 program to determine whether
# given expression is balanced/ parenthesis
# expression or not.
# Function to check if two brackets are
# matching or not.
def isMatching(a, b):
if ((a == '{' and b == '}') or
(a == '[' and b == ']') or
(a == '(' and b == ')') or
a == 'X'):
return 1
return 0
# Recursive function to check if given
# expression is balanced or not.
def isBalanced(s, ele, ind):
# Base case.
# If the string is balanced then all the
# opening brackets had been popped and
# stack should be empty after string is
# traversed completely.
if (ind == len(s)):
if len(ele) == 0:
return True
else:
return False
# Variable to store element at the top
# of the stack.
# char topEle;
# Variable to store result of
# recursive call.
# int res;
# Case 1: When current element is an
# opening bracket then push that
# element in the stack.
if (s[ind] == '{' or s[ind] == '(' or
s[ind] == '['):
ele.append(s[ind])
return isBalanced(s, ele, ind + 1)
# Case 2: When current element is a closing
# bracket then check for matching bracket
# at the top of the stack.
elif (s[ind] == '}' or s[ind] == ')' or
s[ind] == ']'):
# If stack is empty then there is no matching
# opening bracket for current closing bracket
# and the expression is not balanced.
if (len(ele) == 0):
return 0
topEle = ele[-1]
ele.pop()
# Check bracket is matching or not.
if (isMatching(topEle, s[ind]) == 0):
return 0
return isBalanced(s, ele, ind + 1)
# Case 3: If current element is 'X' then check
# for both the cases when 'X' could be opening
# or closing bracket.
elif (s[ind] == 'X'):
tmp = ele
tmp.append(s[ind])
res = isBalanced(s, tmp, ind + 1)
if (res):
return 1
if (len(ele) == 0):
return 0
ele.pop()
return isBalanced(s, ele, ind + 1)
# Driver Code
s = "{(X}[]"
ele = []
# Check if the length of the given string is even
if(len(s)%2==0):
if (isBalanced(s, ele, 0)): print("Balanced")
else: print("Not Balanced")
# If the length is not even, then the string is not balanced
else: print("Not Balanced")
# This code is contributed by divyeshrabadiya07
|
linear
|
np
|
# Python program for an efficient solution to check if
# a given array can represent Preorder traversal of
# a Binary Search Tree
INT_MIN = -2**32
def canRepresentBST(pre):
# Create an empty stack
s = []
# Initialize current root as minimum possible value
root = INT_MIN
# Traverse given array
for value in pre:
#NOTE:value is equal to pre[i] according to the
#given algo
# If we find a node who is on the right side
# and smaller than root, return False
if value < root :
return False
# If value(pre[i]) is in right subtree of stack top,
# Keep removing items smaller than value
# and make the last removed items as new root
while(len(s) > 0 and s[-1] < value) :
root = s.pop()
# At this point either stack is empty or value
# is smaller than root, push value
s.append(value)
return True
# Driver Program
pre1 = [40 , 30 , 35 , 80 , 100]
print ("true" if canRepresentBST(pre1) == True else "false")
pre2 = [40 , 30 , 35 , 20 , 80 , 100]
print ("true" if canRepresentBST(pre2) == True else "false")
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
linear
|
linear
|
# Python3 program to illustrate if a given array can represent
# a preorder traversal of a BST or not
import sys
preIndex = 0
# We are actually not building the tree
def buildBST_helper(n, pre, Min, Max):
global preIndex
if (preIndex >= n):
return
if (Min <= pre[preIndex] and pre[preIndex] <= Max):
# build node
rootData = pre[preIndex]
preIndex+=1
# build left subtree
buildBST_helper(n, pre, Min, rootData)
# build right subtree
buildBST_helper(n, pre, rootData, Max)
# else
# return NULL
def canRepresentBST(arr, N):
global preIndex
# code here
Min, Max = sys.maxsize, -sys.maxsize
buildBST_helper(N, arr, Min, Max)
if preIndex == N:
return True
return False
preorder1 = [ 2, 4, 3 ]
"""
2
\
4
/
3
"""
n1 = len(preorder1)
if (not canRepresentBST(preorder1, n1)):
print("preorder1 can represent BST");
else:
print("preorder1 can not represent BST :(")
preorder2 = [ 5, 3, 4, 1, 6, 10 ]
n2 = len(preorder2)
"""
5
/ \
3 1
\ / \
4 6 10
"""
if (canRepresentBST(preorder2, n2)):
print("preorder2 can represent BST")
else:
print("preorder2 can not represent BST :(")
preorder3 = [ 5, 3, 4, 8, 6, 10 ]
n3 = len(preorder3)
"""
5
/ \
3 8
\ / \
4 6 10
"""
if (not canRepresentBST(preorder3, n3)):
print("preorder3 can represent BST")
else:
print("preorder3 can not represent BST :(")
|
logn
|
linear
|
# Python program to find the difference b/w left and
# right smaller element of every element in the array
# Function to fill left smaller element for every
# element of arr[0..n-1]. These values are filled
# in SE[0..n-1]
def leftsmaller(arr, n, SE):
# create an empty stack
sta = []
# Traverse all array elements
# compute nearest smaller elements of every element
for i in range(n):
# Keep removing top element from S while the top
# element is greater than or equal to arr[i]
while(sta != [] and sta[len(sta)-1] >= arr[i]):
sta.pop()
# Store the smaller element of current element
if(sta != []):
SE[i]=sta[len(sta)-1]
# If all elements in S were greater than arr[i]
else:
SE[i]=0
# push this element
sta.append(arr[i])
# Function returns maximum difference b/w Left &
# right smaller element
def findMaxDiff(arr, n):
ls=[0]*n # to store left smaller elements
rs=[0]*n # to store right smaller elements
# find left smaller elements of every element
leftsmaller(arr, n, ls)
# find right smaller element of every element
# by sending reverse of array
leftsmaller(arr[::-1], n, rs)
# find maximum absolute difference b/w LS & RRS
# In the reversed array right smaller for arr[i] is
# stored at RRS[n-i-1]
res = -1
for i in range(n):
res = max(res, abs(ls[i] - rs[n-1-i]))
# return maximum difference b/w LS & RRS
return res
# Driver Program
if __name__=='__main__':
arr = [2, 4, 8, 7, 7, 9, 3]
print "Maximum Diff :", findMaxDiff(arr, len(arr))
#Contributed By: Harshit Sidhwa
|
linear
|
linear
|
# Python 3 Program to find Right smaller element of next
# greater element
# function find Next greater element
def nextGreater(arr, n, next, order):
S = []
# Traverse all array elements in reverse order
# order == 'G' we compute next greater elements of
# every element
# order == 'S' we compute right smaller element of
# every element
for i in range(n-1,-1,-1):
# Keep removing top element from S while the top
# element is smaller than or equal to arr[i] (if Key is G)
# element is greater than or equal to arr[i] (if order is S)
while (S!=[] and (arr[S[len(S)-1]] <= arr[i]
if (order=='G') else arr[S[len(S)-1]] >= arr[i] )):
S.pop()
# store the next greater element of current element
if (S!=[]):
next[i] = S[len(S)-1]
# If all elements in S were smaller than arr[i]
else:
next[i] = -1
# Push this element
S.append(i)
# Function to find Right smaller element of next greater
# element
def nextSmallerOfNextGreater(arr, n):
NG = [None]*n # stores indexes of next greater elements
RS = [None]*n # stores indexes of right smaller elements
# Find next greater element
# Here G indicate next greater element
nextGreater(arr, n, NG, 'G')
# Find right smaller element
# using same function nextGreater()
# Here S indicate right smaller elements
nextGreater(arr, n, RS, 'S')
# If NG[i] == -1 then there is no smaller element
# on right side. We can find Right smaller of next
# greater by arr[RS[NG[i]]]
for i in range(n):
if (NG[i] != -1 and RS[NG[i]] != -1):
print(arr[RS[NG[i]]],end=" ")
else:
print("-1",end=" ")
# Driver program
if __name__=="__main__":
arr = [5, 1, 9, 2, 5, 1, 7]
n = len(arr)
nextSmallerOfNextGreater(arr, n)
# this code is contributed by ChitraNayal
|
linear
|
linear
|
# Python program to calculate maximum sum with equal
# stack sum.
# Returns maximum possible equal sum of three stacks
# with removal of top elements allowed
def maxSum(stack1, stack2, stack3, n1, n2, n3):
sum1, sum2, sum3 = 0, 0, 0
# Finding the initial sum of stack1.
for i in range(n1):
sum1 += stack1[i]
# Finding the initial sum of stack2.
for i in range(n2):
sum2 += stack2[i]
# Finding the initial sum of stack3.
for i in range(n3):
sum3 += stack3[i]
# As given in question, first element is top
# of stack..
top1, top2, top3 = 0, 0, 0
ans = 0
while (1):
# If any stack is empty
if (top1 == n1 or top2 == n2 or top3 == n3):
return 0
# If sum of all three stack are equal.
if (sum1 == sum2 and sum2 == sum3):
return sum1
# Finding the stack with maximum sum and
# removing its top element.
if (sum1 >= sum2 and sum1 >= sum3):
sum1 -= stack1[top1]
top1=top1+1
else if (sum2 >= sum1 and sum2 >= sum3):
sum2 -= stack2[top2]
top2=top2+1
else if (sum3 >= sum2 and sum3 >= sum1):
sum3 -= stack3[top3]
top3=top3+1
# Driven Program
stack1 = [ 3, 2, 1, 1, 1 ]
stack2 = [ 4, 3, 2 ]
stack3 = [ 1, 1, 4, 1 ]
n1 = len(stack1)
n2 = len(stack2)
n3 = len(stack3)
print (maxSum(stack1, stack2, stack3, n1, n2, n3))
#This code is contributed by Afzal Ansari
|
constant
|
linear
|
# Python3 program to count the number less
# than N, whose all permutation is greater
# than or equal to the number.
# Return the count of the number having
# all permutation greater than or equal
# to the number.
def countNumber(n):
result = 0
# Pushing 1 to 9 because all number
# from 1 to 9 have this property.
s = []
for i in range(1, 10):
if (i <= n):
s.append(i)
result += 1
# take a number from stack and add
# a digit smaller than or equal to last digit
# of it.
while len(s) != 0:
tp = s[-1]
s.pop()
for j in range(tp % 10, 10):
x = tp * 10 + j
if (x <= n):
s.append(x)
result += 1
return result
# Driver Code
if __name__ == '__main__':
n = 15
print(countNumber(n))
# This code is contributed by PranchalK
|
linear
|
linear
|
# Python program to decode a string recursively
# encoded as count followed substring
# Returns decoded string for 'str'
def decode(Str):
integerstack = []
stringstack = []
temp = ""
result = ""
i = 0
# Traversing the string
while i < len(Str):
count = 0
# If number, convert it into number
# and push it into integerstack.
if (Str[i] >= '0' and Str[i] <='9'):
while (Str[i] >= '0' and Str[i] <= '9'):
count = count * 10 + ord(Str[i]) - ord('0')
i += 1
i -= 1
integerstack.append(count)
# If closing bracket ']', pop element until
# '[' opening bracket is not found in the
# character stack.
elif (Str[i] == ']'):
temp = ""
count = 0
if (len(integerstack) != 0):
count = integerstack[-1]
integerstack.pop()
while (len(stringstack) != 0 and stringstack[-1] !='[' ):
temp = stringstack[-1] + temp
stringstack.pop()
if (len(stringstack) != 0 and stringstack[-1] == '['):
stringstack.pop()
# Repeating the popped string 'temo' count
# number of times.
for j in range(count):
result = result + temp
# Push it in the character stack.
for j in range(len(result)):
stringstack.append(result[j])
result = ""
# If '[' opening bracket, push it into character stack.
elif (Str[i] == '['):
if (Str[i-1] >= '0' and Str[i-1] <= '9'):
stringstack.append(Str[i])
else:
stringstack.append(Str[i])
integerstack.append(1)
else:
stringstack.append(Str[i])
i += 1
# Pop all the element, make a string and return.
while len(stringstack) != 0:
result = stringstack[-1] + result
stringstack.pop()
return result
# Driven code
if __name__ == '__main__':
Str = "3[b2[ca]]"
print(decode(Str))
# This code is contributed by PranchalK.
|
linear
|
linear
|
def decodeString(s):
st = []
for i in range(len(s)):
# When ']' is encountered, we need to start decoding
if s[i] == ']':
temp = ""
while len(st) > 0 and st[-1] != '[':
# st.top() + temp makes sure that the
# string won't be in reverse order eg, if
# the stack contains 12[abc temp = c + "" =>
# temp = b + "c" => temp = a + "bc"
temp = st[-1] + temp
st.pop()
# remove the '[' from the stack
st.pop()
num = ""
# remove the digits from the stack
while len(st) > 0 and ord(st[-1]) >= 48 and ord(st[-1]) <= 57:
num = st[-1] + num
st.pop()
number = int(num)
repeat = ""
for j in range(number):
repeat += temp
for c in range(len(repeat)):
if len(st) > 0:
if repeat == st[-1]:
break #otherwise this thingy starts appending the same decoded words
st.append(repeat)
else:
st.append(s[i])
return st[0]
Str = "3[b2[ca]]"
print(decodeString(Str))
# This code is contributed by mukesh07.
# And debugged by ivannakreshchenetska
|
linear
|
linear
|
# Python3 program for bubble sort
# using stack
# Function for bubble sort using Stack
def bubbleSortStack(a, n):
s1 = []
# Push all elements of array in 1st stack
for i in range(n):
s1.append(a[i]);
s2 = []
for i in range(n):
if (i % 2 == 0):
while (len(s1) != 0):
t = s1[-1]
s1.pop();
if(len(s2) == 0):
s2.append(t);
else:
# Swapping
if (s2[-1] > t):
temp = s2[-1]
s2.pop();
s2.append(t);
s2.append(temp);
else:
s2.append(t);
# Tricky step
a[n - 1 - i] = s2[-1]
s2.pop();
else:
while(len(s2) != 0):
t = s2[-1]
s2.pop();
if(len(s1) == 0):
s1.append(t);
else:
if (s1[-1] > t):
temp = s1[-1]
s1.pop();
s1.append(t);
s1.append(temp);
else:
s1.append(t);
# Tricky step
a[n - 1 - i] = s1[-1]
s1.pop();
print("[", end = '')
for i in range(n):
print(a[i], end = ', ')
print(']', end = '')
# Driver code
if __name__=='__main__':
a = [ 15, 12, 44, 2, 5, 10 ]
n = len(a)
bubbleSortStack(a, n);
# This code is contributed by rutvik_56.
|
linear
|
quadratic
|
# Python program to print all ancestors of a given key
# A class to create a new tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# Iterative Function to print all ancestors of a
# given key
def printAncestors(root, key):
if (root == None):
return
# Create a stack to hold ancestors
st = []
# Traverse the complete tree in postorder way till
# we find the key
while (1):
# Traverse the left side. While traversing, push
# the nodes into the stack so that their right
# subtrees can be traversed later
while (root and root.data != key):
st.append(root) # push current node
root = root.left # move to next node
# If the node whose ancestors are to be printed
# is found, then break the while loop.
if (root and root.data == key):
break
# Check if right sub-tree exists for the node at top
# If not then pop that node because we don't need
# this node any more.
if (st[-1].right == None):
root = st[-1]
st.pop()
# If the popped node is right child of top,
# then remove the top as well. Left child of
# the top must have processed before.
while (len(st) != 0 and st[-1].right == root):
root = st[-1]
st.pop()
# if stack is not empty then simply set the root
# as right child of top and start traversing right
# sub-tree.
root = None if len(st) == 0 else st[-1].right
# If stack is not empty, print contents of stack
# Here assumption is that the key is there in tree
while (len(st) != 0):
print(st[-1].data,end = " ")
st.pop()
# Driver code
if __name__ == '__main__':
# Let us construct a binary tree
root = newNode(1)
root.left = newNode(2)
root.right = newNode(7)
root.left.left = newNode(3)
root.left.right = newNode(5)
root.right.left = newNode(8)
root.right.right = newNode(9)
root.left.left.left = newNode(4)
root.left.right.right = newNode(6)
root.right.right.left = newNode(10)
key = 6
printAncestors(root, key)
# This code is contributed by PranchalK.
|
linear
|
linear
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.