diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 0000000..0921d0a --- /dev/null +++ b/Problem1.py @@ -0,0 +1,81 @@ +# Time Complexity --> O(m*n) will be the amortized complexity. As the number of initial rotten oranges increases, the number of times revisiting an orange will decrease since the distance increases. +# Space Complexity --> O(m*n) +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + m = len(grid) + n = len(grid[0]) + self.dirs = [(0,1),(1,0),(0,-1),(-1,0)] + for i in range(m): + for j in range(n): + if grid[i][j]==2: + self.dfs(grid, i, j, 2) + + maxi = 2 + for i in range(m): + for j in range(n): + if grid[i][j]==1: + return -1 + maxi = max(maxi, grid[i][j]) + return maxi-2 + + + def dfs(self, grid, r, c, time): + #base + if r<0 or c<0 or r==len(grid) or c==len(grid[0]): + return + if grid[r][c]!=1 and grid[r][c] O(m*n) +# Space Complexity --> O(m*n) + +from collections import deque +class Solution: + def orangesRotting(self, grid: List[List[int]]) -> int: + q = deque() + m = len(grid) + n = len(grid[0]) + fresh = 0 + + for i in range(m): + for j in range(n): + if grid[i][j]==2: + q.append((i,j)) + elif grid[i][j]==1: + fresh += 1 + + if len(q)==0 and fresh==0: + return 0 + + dirs = [(0,1),(1,0),(0,-1),(-1,0)] + time = 0 + while len(q)>0: + size = len(q) + for i in range(size): + curr = q.popleft() + for dir in dirs: + nr = curr[0] + dir[0] + nc = curr[1] + dir[1] + if nr>=0 and nr=0 and nc0: + return -1 + return time-1 + +''' diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 0000000..368b123 --- /dev/null +++ b/Problem2.py @@ -0,0 +1,46 @@ +""" +# Definition for Employee. +class Employee: + def __init__(self, id: int, importance: int, subordinates: List[int]): + self.id = id + self.importance = importance + self.subordinates = subordinates +""" +# Time Complexity --> O(n) +# Space Complexity --> O(n) +# Approach --> DFS +class Solution: + def getImportance(self, employees: List['Employee'], id: int) -> int: + hmap = {} + for emp in employees: + hmap[emp.id] = emp + self.result = 0 + self.dfs(id, hmap) + return self.result + + def dfs(self, id, hmap): + self.result += hmap[id].importance + for subordinate in hmap[id].subordinates: + self.dfs(subordinate, hmap) + + +''' +# Time Complexity --> O(n) +# Space Complexity --> O(n) +# Approach --> BFS +class Solution: + def getImportance(self, employees: List['Employee'], id: int) -> int: + hmap = {} + for e in employees: + hmap[e.id] = e + q = deque() + q.append(id) + result = 0 + while len(q)>0: + currid = q.popleft() + curremp = hmap[currid] + result += curremp.importance + for subordinate in curremp.subordinates: + q.append(subordinate) + return result +'''