Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions EmployeeImportance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//Time complexity : O(n) where m is the number of employees
//Space complexity : O(n) where m is the number of employees
/*
// Definition for Employee.
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
};
*/

class Solution {
int result = 0;
Map<Integer, Employee> idToEmployee = new HashMap<>();

public int getImportance(List<Employee> employees, int id) {

for (Employee employee : employees) {
idToEmployee.put(employee.id, employee);
}

dfs(id);
return result + idToEmployee.get(id).importance;
}

void dfs(int id) {
if (idToEmployee.get(id).subordinates == null || idToEmployee.get(id).subordinates.size() == 0) {
return;
}

for (int subId : idToEmployee.get(id).subordinates) {
result += idToEmployee.get(subId).importance;
dfs(subId);
}
}
}
62 changes: 62 additions & 0 deletions RottingOranges.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//Time complexity : O(mn) where m is the number of rows, n is the number of columns
//Space complexity : O(mn) where m is the number of rows, n is the number of columns

class Solution {
int result;
int fresh;
public int orangesRotting(int[][] grid) {
Queue<int[]> queue = new LinkedList<>();
int[][] dirs = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
result = 0;
fresh = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 2) {
queue.add(new int[] { i, j });
} else if (grid[i][j] == 1) {
fresh++;
}
}
}

if (fresh == 0) {
return result;
}

bfs(queue, grid, dirs, m, n);
if (fresh != 0) {
return -1;
}
return result;

}

void bfs(Queue<int[]> queue, int[][] grid, int[][] dirs, int m, int n) {
while (!queue.isEmpty()) {
result++;
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] coord = queue.poll();

for (int[] dir : dirs) {
int row = coord[0] + dir[0];
int col = coord[1] + dir[1];
if (row >= 0 && col >= 0 && row < m && col < n && grid[row][col] == 1) {
int neighbor = grid[row][col];
queue.add(new int[] { row, col });
grid[row][col] = 2;
fresh--;
}
}
if (fresh == 0) {
break;
}
}
if (fresh == 0) {
break;
}
}
}
}